How to signify no more input for string ss in the loop while (cin >> ss)

前端 未结 10 1413
情书的邮戳
情书的邮戳 2020-11-29 09:12

I used \"cin\" to read words from input stream, which like

int main( ){
     string word;
     while (cin >> word){
         //do sth on the input word         


        
相关标签:
10条回答
  • 2020-11-29 10:11

    It helps me to terminate loop by hitting ENTER.

    int main() {
        string word;
        while(getline(cin,word) && s.compare("\0") != 0) {
            //do sth on the input word
        }
    
        // perform some other operations
    }
    0 讨论(0)
  • 2020-11-29 10:12

    Take the input from a file. Then you will find that the while loop terminates when your program stops taking input. Actually cin stops taking input when it finds an EOF marker. Each input file ends with this EOF marker. When this EOF marker is encountered by operator>> it modifies the value of internal flag eofbit into false and consequently the while loop stops.

    0 讨论(0)
  • 2020-11-29 10:12

    your program doesn't take in count white spaces. make difference between cin and getline...

    here is an example with a trick: the program get input and prints output until you hit twice Enter to quit:

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main(){
    
    
        char c = '\0';
        string word;
        int nReturn = 0;
    
        cout << "Hit Enter twice to quit\n\n";
    
        while (cin.peek())
        {
            cin.get(c);
    
            if(nReturn > 1)
                break;
            if('\n' == c)
                nReturn++;
            else
                nReturn = 0;
            word += c;
            cout << word;
            word = "";
        }
    
        cout << endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-29 10:13

    As others already answer this question, I would like add this important point:

    Since Ctrl-Z on Windows (and Ctrl-D on unix systems) causes EOF to reach, and you exit from the while loop, but outside the while loop you cannot read further input, since the EOF is already reached.

    So to enable reading using cin again, you need to clear eof flag, and all other failure flags, as shown below:

    cin.clear();
    

    After doing this, you can start reading input using cin once again!

    0 讨论(0)
提交回复
热议问题