I'm trying to figure out how to write a few functions to check a user's input before continuing the program. Specifically, I'm trying to use the isdigit fuction to check if an integer really had an integer inputted to it, and not a letter or character. Most of the examples I've seen have it checking a string, so should I make a string value equal to the integer as a way to check? I'm kind of at a loss here. What do you, the experts have to say?
I'm sorry, but I can't seem to get that code working. What I'm trying to do is protect when a user enters, say "Y" instead of say, "19.99" in that code.
The top one worked, so I think I'll be using that from now on to test numbers. I'm not sure about testing characters or strings yet, but there's a few more things I'll try before asking for help. Thank you.
I'm just not understanding why that works. How does that test an integer to see if an integer value was entered?
The >> operator is actually a function call to read in characters and convert them to whatever type you are asking for. In this case a float. If the input does not conform to a number, then a flag is set. So you are basically testing that flag when you use >>
I don't know what was happening before, but suddenly now your code is working. I probably dropped a semi-colon somewhere. Now I just have to make this work in a while loop while asking for new input. Thanks for helping me understand.
Alright, the while loop seems to be working backwards. I wrote it like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
int test;
cout<< "Enter a number";
cin>> test;
while (std::cin >> test)
{
cout<< "Enter a number";
cin>> test;
}
std::cin.clear();
return (0);
}
The while loop still executes when a valid entry is entered, and you have to make 2 entries. The loop stops when an invalid entry in entered. I tried using while (!std::cin >> test) , and it's skipped when there is a valid entry, but an invalid entry causes a loop of text. Any ideas about that?
Okay, new question. Is it practical to have all entries be stings, test them with isdigit or isalpah and then convert them to the data types that I need them to be for calculations?
See, that was my mistake too. I didn't know to put the std::cin in paranthesis. Now, it's close. For some reason I have to put in a valid entry (number) twice. I'm not entirely sure why. Everything else works. Sorry to rack your brain with this.