0

My code is:

unsigned numbers, x = 0, odds = 0;
cout << "Input numbers to find the amount of odds. " << endl;
while ( x < 9999 ){
    cin >> numbers || die("Input Error");
    if (numbers % 2 == 1) {
        odds++;
    }
}
cout << "There are " << odds << " odds." << endl;

return 0;

How can I quit the loop when the user inputs a non-numeric value for numbers? Thank you in advanced.

  • 1
    Possible duplicate of [Reading 'unsigned int' using 'cin'](http://stackoverflow.com/questions/9574771/reading-unsigned-int-using-cin) – cadaniluk Oct 20 '15 at 18:31

4 Answers4

1

You can make the input a condition of the loop.

while (cin >> numbers)
{
    //...
}

Will run until the user enters something that cannot be inputted into numbers. If you want to have the check the numbers < 9999 as well then we would have

while (std::cin >> numbers && numbers < 9999)
{
    //...
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • this is incorrect. see: https://stackoverflow.com/questions/7465494/how-to-compare-an-ascii-value – Nandu Oct 20 '15 at 18:54
  • @Nandu What? That has nothing to do with this and it is wrong language. – NathanOliver Oct 20 '15 at 18:55
  • @Nandu The question was "How can I quit the loop when the user inputs a non-numeric value for numbers?" How is "123a" a numeric value? – cdonat Oct 20 '15 at 19:31
  • @Nandu It will pick up the 123 and then terminate after processing it. This as good as the OP can get without doing a bunch of string processing. – NathanOliver Oct 20 '15 at 19:32
0
#include <cctype>
std::string str;
cin >> str;
for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
 if (!std::isdigit(*it)) {
   cout << "non-digit");
   return;
}
Nandu
  • 808
  • 7
  • 10
0

The keyword you are looking for is break:

while ( x < 9999 ) {
    if((cin >> numbers).fail())
        break;

    if (numbers % 2 == 1) {
        odds++;
    }
}
cdonat
  • 2,748
  • 16
  • 24
  • incorrect. see: https://stackoverflow.com/questions/7465494/how-to-compare-an-ascii-value – Nandu Oct 20 '15 at 18:55
  • @Nandu can you please elaborate, why you think, this is incorrect? Your link is completely unrelated to the question and to my answer. – cdonat Oct 20 '15 at 19:19
-1

Use hash_fun to evaluate the strings and ingnore any non numeric values