0

My program is supposed to create hashes for our class. I have it working the only requirement I'm missing is that it is supposed to return invalid whenever a # is found so I added a line that I hoped would fix it but I still get the same result where only a few numbers truly return the INVALID INPUT What its supposed to do is say: hello hash is 21 but if it was 24hello then it should return INVALID INPUT

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>

using namespace std;

string userInput;
int strNum = 0;
int hashOfStr = 0;
bool hasDigit = false;


int strScore(string str[], string s, int n, int index){
   int score = 0;
   for (int j = 0; j < s.length(); j++)
   {
        if(s[j]=='0'||s[j]=='1'||s[j]=='2'||s[j]=='3'||s[j]=='5'||s[j]=='6'||s[j]=='7'||s[j]=='8'||s[j]=='9')
        {
            hasDigit = true;
        }
       if(s[j]!=' '){
            score += s[j] - 'a' + 1;
            cout << s[j] << endl;

       }
   }
   score *= index;
   return score;
}

string getSentence()
{
    cout << "Mod Hashing: " << endl;
    cout << "Enter Sentence To Be Hashed(0 To Quit): ";
    getline(cin, userInput);
    for_each(userInput.begin(), userInput.end(), [](char & c) {
        c = tolower(c);
    });
    cout << endl;
    return userInput;
}





int main()
{
    while(userInput != "0")
    {
        getSentence();
        string str[] = {userInput};
        int n = sizeof(str) / sizeof(str[0]);
        string s = str[0];
        if(hasDigit == false)
        {
            for(int i = 0; i < n; i++)
            {
                s = str[i];
                strNum = strScore(str, s, n, i+1);
            }
                hashOfStr = strNum % 31;
                cout << "Hash of: " << userInput << " is " << hashOfStr << endl << endl;
            }
        else if(hasDigit == true)
        {
            cout << "INVALID INPUT" << endl;
            hasDigit = false;
        }
    }
    return 0;
}
  • [`std::stoi`](https://en.cppreference.com/w/cpp/string/basic_string/stol) can be used to both convert a string to `int` as well as help with validation. Use [`std::strtol`](https://en.cppreference.com/w/cpp/string/byte/strtol) If you don't want exceptions. – Some programmer dude Sep 14 '20 at 00:48
  • 2
    Usage of `std::any_of` to determine if there is a digit will remove that entire loop you've written and that very long `if` statement. `std::any_of(s.begin(), s.end(), ::isdigit )` returns `true` if there is a digit in the string. – PaulMcKenzie Sep 14 '20 at 00:49
  • For explicit validation [`std::isdigit`](https://en.cppreference.com/w/cpp/string/byte/isdigit) could be helpful. – Some programmer dude Sep 14 '20 at 00:50

0 Answers0