Is there a way to check what int a string has? For example, a string named "Choice" holds the value of "A1". I can find the 'A' with Choice[0] == "A'. When I try if Choice[1] == 1, it returns nothing.
string str = "A1B3Apple35C8";
for(int i = 0; i<str.size(); i++)
if(isalpha(str[i])) cout << "character " << i << " in string \"str\" is: " << str[i] << " which is a letter." << endl;
else cout << "character " << i << " in string \"str\" is: " << str[i] << " which is a number." << endl;
oh and by the way it would have to be "1" not 1 if you are doing the == because it still is a cosnt char (string) not an int. if you wish to convert it to an int you would have to do int num = atoi(choice[positionof1]);
Thank you for the help, but I have a couple of questions.
Can you explain isalpha to me? I looked it up in the reference section but still didn't get it. In your code, why does it even print letters? I thought it was only for checking numbers?
Also, I can't put the 1 in quotes or I get this error:
operand types are incompatible ("char" and "const char *")
Finally, what's the difference between isdigit, isalpha, stoi, and atoi? I looked them up in the reference section and they seem to do exactly the same thing.
@giblit Your code is flawed. Your if statement if(isalpha(str[i])) evaluates to true if the input is a letter. In your code anything that isn't a letter is considered a number. So the '!', '?', '.' and '@' characters are all considered numbers. Why not use the function designed specifically for the purpose of finding digits?
@yayu This if statement will work if(Choice[1] == 1) if you put the 1 in single quotes. if(Choice[1] == '1')
isdigit checks to see of a character is a digit
isalpha checks to see if a character is a letter
stoi converts a string to an integer (class string)
atoi converts a cstring to an integer (char array)