如何按行读取输入,然后按单词分隔

How do I read input by line and then separate by word?

本文关键字:单词 分隔 然后 何按行 读取 输入      更新时间:2023-10-16

我正试图从用户那里获取一个短语,并颠倒单词的顺序,然后将其打印出来。例如,"hello-world"变为"world-hello"。

我在这里发现了其他类似于我的问题,大多数"投票支持"的答案都建议这样做:

std::list<std::string> input;
std::list<std::string>::iterator iter;
std::string phrase;
std::string word;
std::cout << " Enter the phrase you wish to reverse " << std::endl;
std::cout << " >> ";
std::getline(std::cin, phrase);
std::istringstream iss(phrase);
while (iss >> word) {
    input.push_front(word);
}
for (iter = input.begin(); iter != input.end(); ++iter) {
    std::cout << *iter << " ";
}

然而,这对我不起作用。当我运行代码时,它从未停止允许输入。我不明白为什么它不允许我输入。

我该如何做到这一点,这样我就可以输入一个短语,并让程序逐字逐句地阅读它?

编辑:我使用的是MS Visual Studio 2015,并使用debug(f5)选项进行编译。

原来在输入流中有一个杂散"\n",我只是简单地调用了

std::cin.get();

以摆脱它。

我认为可能是这样,但我想不出如何"刷新"输入流,因为cin没有刷新方法。

非常感谢Ankur Jyoti Phukan的帮助!