如何在C++中结束一个句子?

hm2xizp9  于 2023-04-08  发布在  其他
关注(0)|答案(4)|浏览(132)

我是Cpp的初学者,试图通过一本名为“使用c++编程原理和实践”(第2版)的书中给出的例子。
为了进一步参考,我正在谈论“4.6.4文本示例”,其中需要将句子作为输入并构建单词字典(排序后)。
上面提到的例子如下。

// simple dictionary: list of sorted words
int main()
{
  vector<string> words;
  for(string temp; cin>>temp; ) // read whitespace-separated words
     words.push_back(temp); // put into vector
  cout << "Number of words: " << words.size() << '\n';
  sort(words); // sort the words
  for (int i = 0; i<words.size(); ++i)
     if (i==0 || words[i–1]!=words[i]) // is this a new word?
        cout << words[i] << "\n";
}

在上面的代码示例第5行(在for循环表达式中),cin〉〉temp对我来说没有意义。为什么?运行代码后,控制台弹出,我开始输入几个单词的句子,甚至在点击enter后,我无法终止字符串并转到下一行?如何在这里终止输入?

wfypjpf4

wfypjpf41#

我不明白为什么

for(string temp; cin>>temp; ) // read whitespace-separated words
     words.push_back(temp); // put into vector

它相当于:

string temp;
while (cin >> temp)
{
    words.push_back(temp);
}

cin>>temp将在到达输入流的末尾时计算为false,并触发循环中断。否则,temp被分配一个字符串,cin>>temp计算为true。

0md85ypi

0md85ypi2#

当程序当前正在编写时,流必须无法读取才能退出循环。当阅读到std::string时,这是很难做到的,string将愉快地吃掉几乎任何东西,而不会关闭输入流。根据所使用的终端软件,在大多数桌面平台上,关闭流可以通过CTRL+D xor CTRL+Z来完成。
请注意,一旦关闭,可能很难再次打开cin,所以通常我会做类似option 2 in this linked answer的事情。从输入流中读取整行,将该行写入第二个流。循环通过第二个流。在行的末尾,第二个流结束,退出循环。
原始代码的简单多行版本可能如下所示

int main()
{
    std::string line;
    while (std::getline(cin, line))
    {
        std::istringstream iss(line); // #include <sstream>
        vector<string> words;
        for(string temp; iss>>temp; ) // read whitespace-separated words
            words.push_back(temp); // put into vector

        cout << "Number of words: " << words.size() << '\n';
        sort(words); // sort the words
        for (int i = 0; i<words.size(); ++i)
            if (i==0 || words[i-1]!=words[i]) // is this a new word?
                cout << words[i] << "\n";
    }
}
e0bqpujr

e0bqpujr3#

>>运算符是overloaded function
operator>>(cin, temp)中真正被称为。
该函数返回流(cin)本身,它具有重载的bool conversion operator,如果流状态良好,则返回true。如果失败,例如文件结束,则返回false
这意味着流和输入操作符可以作为布尔条件的一部分来读取,直到到达文件结束。

dkqlctbz

dkqlctbz4#

如果输入操作失败,cin >> temp将计算为false。阅读string时最常见的失败是到达文件结尾,这就是您想要导致的情况。
在大多数Linux(或其他POSIX)shell中,输入文件结束标记的方法是按ctrl+d,而在Windows控制台主机中是按ctrl+x
或者,您可以使用管道将其输入连接到其他命令的输出,而不是直接与程序交互。当生成输出的命令终止并关闭管道的末尾时,您的程序将看到文件结束条件。例如,类似于以下内容的内容几乎适用于任何shell:

echo "this is some text" | your-program

或者,使用大多数现代的POSIX shell,你可以使用heredoc,它的工作原理和上面的基本相同,但是shell本身写入程序的输入流,而不是挂接一个外部命令来完成。

your-program <<EOF
this is some text
EOF

相关问题