繁体   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