cin.eof() functionality

前端 未结 8 1220
夕颜
夕颜 2021-01-11 13:40

I understand that cin.eof() tests the stream format. And while giving input, end of character is not reached when there is wrong in the input. I tested

8条回答
  •  独厮守ぢ
    2021-01-11 13:49

    cin.eof() test if the stream has reached end of file which happens if you type something like Ctrl+C (on Windows), or if input has been redirected to a file etc.

    To test if the input contains an integer and nothing but an integer, you can get input first into a string and then convert that with a stringstream. A stringstream indeed reaches eof if there's no more to be extracted from it.

    #include 
    #include 
    #include 
    
    int main() {
        using namespace std;
        int i;
        string input;
        cin >> input; //or getline(cin, input)
        stringstream ss(input);
        if (ss >> i && ss.eof()) {  //if conversion succeeds and there's no more to get
            cout<< "\n Correct Input \n";
        }
        else {
            cout<< "\n Format Error \n";
        }
    
      return 0;
    }
    

提交回复
热议问题