簡體   English   中英

如何表示循環中不再有字符串 ss 的輸入 while (cin >> ss)

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

我使用“cin”從輸入流中讀取單詞,例如

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

    // perform some other operations
}

代碼結構類似於上面的那種。 它是可編譯的。 在執行過程中,我不斷輸入類似

aa bb cc dd

我的問題是如何結束這個輸入? 換句話說,假設文本文件只是“aa bb cc dd”。 但我不知道如何讓程序知道文件結束了。

你的代碼是正確的。 如果是交互式輸入,則需要發送 EOF 字符,例如 CTRL-D。

讀取文件時不需要此 EOF 字符。 這是因為一旦到達輸入流的末尾,“cin”就沒有任何剩余(因為流現在已關閉),因此 while 循環退出。

由於其他人已經回答了這個問題,我想補充一點:

由於 Windows 上的 Ctrl-Z(以及 unix 系統上的 Ctrl-D)導致到達 EOF,並且您退出while循環,但在while循環之外您無法讀取進一步的輸入,因為已經到達 EOF。

因此,要再次使用cin啟用讀取,您需要清除eof標志和所有其他失敗標志,如下所示:

cin.clear();

完成此操作后,您可以再次使用cin開始讀取輸入!

int main() {
     string word;
     while (cin >> word) {
         // do something on the input word.
         if (foo)
           break;
     }
    // perform some other operations.
}

按 Ctrl-Z(在 *nix 系統上按 Ctrl-D)並按 Enter。 這會發送一個 EOF 並使流無效。

cin >> some_variable_or_manipulator將始終評估為對cin的引用。 如果您想檢查並查看是否還有更多輸入要閱讀,您需要執行以下操作:

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

    // perform some other operations
}

這會檢查流的 goodbit,當 eofbit、failbit 或 badbit 都沒有設置時,它被設置為 true。 如果讀取錯誤,或流收到 EOF 字符(來自到達文件末尾或來自鍵盤上的用戶按 CTRL+D),cin.good() 將返回 false,並使您擺脫環形。

從文件中獲取輸入。 然后你會發現當你的程序停止接受輸入時,while 循環就終止了。 實際上, cin在找到 EOF 標記時停止接受輸入。 每個輸入文件都以這個 EOF 標記結束。 operator>>遇到這個 EOF 標記時,它將內部標志eofbit的值修改為 false,因此 while 循環停止。

它可以幫助我通過按 ENTER 來終止循環。

int main() {
    string word;
    while(getline(cin,word) && s.compare("\0") != 0) {
        //do sth on the input word
    }

    // perform some other operations
}

您可以檢查輸入中的特殊單詞。 鐵“停止”:

int main( ){
   string word;

   while (cin >> word){
      if(word == "stop")
          break;

      //do sth on the input word
   }

// perform some other operations
}

我猜你想在文件末尾跳出。 您可以獲取basic_ios::eof的值,它在流結束時返回 true。

你可以試試這個

    string word;
    vector<string> words;
    while (cin >> word) {
                                            
        words.push_back(word);
        if (cin.get() == '\n')
            break;
    }

這樣,您就不必以 CTRL+D(Z) 結尾。 程序將在句子結束時退出

您的程序不考慮空格。 cin 和 getline 之間的區別...

這是一個帶有技巧的示例:程序獲取輸入並打印輸出,直到您按兩次 Enter 退出:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM