简体   繁体   中英

Infinite Loop when checking conditions c++ !cin

I'm basically expecting a number as input. The magnitude is negligible now as I know my else if loop works fine. But testing if its a number proves to be a bit trickier. I just want to call the function again and start over if the user enters in something alphanumeric or just plain words. Or pressed enter. Something that is not a number. I tried !cin since I am inputting into int numTemp , but that just results in an infinite loop that spills out "what is the bitrate" countless times. Anyone know what I'm doing wrong? I tried putting cin.clear() and cin.ignore(100, "\\n") inside the first if statement but to no avail. Thanks in advance.

bool iTunes::setBitRate()
{
cout << "What is the bitrate? ";
int numTemp;
cin >> numTemp;
if (!cin)
{
    cout << "WRONG" << endl;
    setBitRate();
}
else if( numTemp < MIN_BITRATE || numTemp > MAX_BITRATE)
{
    cout << "Bit Rate out of range" << endl;
    setBitRate();
}
else
{
    bitRate = numTemp;
}
}

您可以只从用户那里读取一个字符串,而不是一个int字符串,然后检查它,并在不喜欢该字符串的情况下提示输入新内容(例如,如果该字符串不能完全转换为数字,则可以使用strtol进行检查) )。

如果要检查输入是数字还是字符,可以使用isdigit ,但是必须将其传递给char ,然后当它是数字时,可以使用atoi将其转换为int

When the statement cin >> numTemp fails due to non-numeric input the character causing the failure is NOT removed from the input stream. So the next time the stream extraction operator is called it will see the same non-numeric input as the last time. To avoid this you need to skip the existing input.

One way of doing this is to use getline() to read a complete line of text before trying to converting it to and integer. The folllowing code snippet illustrates this:

#include <cstdlib>

bool getint(istream& in, int & out) {
    string line;
    getline(in, line);
    char* endptr;
    out = strtol(line.c_str(), &endptr, 10);
    return endptr!=line.c_str();
}

bool iTunes::setBitRate()
{
    cout << "What is the bitrate? ";
    int numTemp;
    if ( !getint(cin, numTemp) && cin )
    {
        cout << "WRONG" << endl;
        setBitRate();
    }
    else if( numTemp < MIN_BITRATE || numTemp > MAX_BITRATE)
    {
        cout << "Bit Rate out of range" << endl;
        setBitRate();
    }
    else
    {
        bitRate = numTemp;
    }
}

NOTE: You should also check the status of cin after each read to ensure that some error has not occurred.

i think this will helps

bool iTunes::setBitRate()
{
  cout << "What is the bitrate? ";
  int numTemp = 0;
  cin >> numTemp;
  if (!numTemp)
  {
    cout << "WRONG" << endl;
    setBitRate();
  }
  else if( numTemp < MIN_BITRATE || numTemp > MAX_BITRATE)
  {
    cout << "Bit Rate out of range" << endl;
    setBitRate();
  }
  else
  {
     bitRate = numTemp;
  }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM