Sep 18, 2016 at 2:40am UTC
Hey everyone, I was recently making a project that requires user input some numbers, however if you type in a char or some random words it goes all crazy. please help me and thx.
Sep 18, 2016 at 2:45am UTC
Could you post your code? This would help to give you a good answer(for your specific case) and not a generic one.
Sep 18, 2016 at 2:48am UTC
Do you absolutly nessarily need the code? I actually just want a general answer... thx for your time though.
Sep 18, 2016 at 2:54am UTC
The "general" answer is to get your input as a string and validate the contents of the string before using them.
Sep 18, 2016 at 2:58am UTC
give me an example please? thx
Sep 18, 2016 at 3:15am UTC
give me an example please? thx
You don't want to supply code, but you wish code to be supplied to you?
There are plenty of examples out in the wild. Visit your favorite search engine.
(For instance a search on this site might lead you to this thread:
http://www.cplusplus.com/forum/beginner/108849/#msg592118 )
Last edited on Sep 18, 2016 at 3:18am UTC
Sep 23, 2016 at 3:24am UTC
help plz... I just want a quick example... thx
Sep 23, 2016 at 11:34am UTC
cin will be flagged as fail if it didn't get the input it wanted. You have to clear the state to do more input operations. Here is a simple example for you...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <string>
using namespace std;
int main()
{
while (true )
{
cout << "give me a number: " ;
int num;
cin >> num;
if (cin.eof() || cin.bad())
break ;
if (cin.fail())
{
cin.clear();
string s;
getline(cin, s);
continue ;
}
cout << "thank you for the number " << num << '\n' ;
}
}
Last edited on Sep 23, 2016 at 12:41pm UTC
Sep 24, 2016 at 5:54pm UTC
thx guys! see i just wanted an example. Was that so hard?
thx again
Sep 24, 2016 at 6:22pm UTC
your example is too complicated, and it is too long. Why do you think i posted this question in beginner's post? krako's post is way easier than yours. though thx.
Last edited on Sep 24, 2016 at 6:23pm UTC