简体   繁体   中英

while Infinite loop in function

bool isDigital(char c) { return ('0' <= c && c <= '9'); }

void DigitalToken( char digitToken[50], char ch ) {
    digitToken[0] = ch;
    char input = '\0';
    cin >> input;
    int i = 0;
    while ( ( input != ' ' ) && ( input != '\t' ) && ( input != '\n' ) ) { // got a infinite loop
        i++;
        digitToken[i] = input;
        cin >> input;
    } // while ( input != ' ' && input != '\t' && input != '\n' )
    
} // DigitalToken()

int main() {
  char ch = '\0';
  while ( cin >> ch ) {
    if ( isDigital(ch) ) {
      char* digitToken = new char[50]();
      DigitalToken(digitToken, ch);
      cout << digitToken;
      delete[] digitToken;
    } // else if
  } // while
} // main()

I don't understand why I got a infinite loop in DitgitalToken function.

When I input 123 , it should be output 123 .

I watched it for a long time, but I still don't know why and how to fix it.

Instead of cin >> input; use input = cin.get(); .

You have to be careful while using cin with characters or strings. It treats spaces, tabs, newlines as end of the input and hence do not treat them as input themselves.

Your program blocks in the while loop on cin >> input; after it read "123". As @Arty suggested use cin.get() instead as whitespace is stripped by default. You can also use cin >> noskipws; prior to executing cin >> input; . See skipws .

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