为什么此代码在遇到换行符之前无法正确读取字符串?

Why doesn't this code correctly read strings until encountering a newline?

本文关键字:读取 字符串 代码 遇到 换行符 为什么      更新时间:2023-10-16

我正在尝试编写一个程序,该程序读取用户的一堆字符串,然后是newline,然后将我阅读的所有字符串推到堆栈上。这是我到目前为止所拥有的:

stack<string> st;
string str;
while(str != "n")
{
    cin >> str;
    st.push(str);
}

但是,这进入无限循环,当我阅读新线时不会停止。为什么会发生这种情况?我该如何修复?

默认情况下,应用于字符串的流提取运算符(>>运算符)将跳过所有空格。如果您输入A B C,则是newline,然后是D E F,然后尝试使用流提取操作员一次读取一个字符串,您将获得字符串" A"," B"," C"," C"," D","e"answers" f",没有空格,也没有新线。

如果您想阅读一堆字符串,直到达到新线,则可以考虑使用 std::getline读取文本行,然后使用 std::istringstream来代币化:

#include <sstream>
/* Read a full line from the user. */
std::string line;
if (!getline(std::cin, line)) {
    // Handle an error
}
/* Tokenize it. */
std::istringstream tokenizer(line);
for (std::string token; tokenizer >> token; ) {
   // Do something with the string token
}

作为注意 - 在原始代码中,您的循环通常看起来像这样:

string toRead;
while (allIsGoodFor(toRead)) {
    cin >> toRead;
    // do something with toRead;
}

通常,这种方法无效,因为它将继续循环一次。具体来说,一旦您阅读了导致条件是错误的输入,循环将继续处理您到目前为止所阅读的内容。这样做可能是一个更好的主意:

while (cin >> toRead && allIsGoodFor(toRead)) {
    do something with toRead;
}

尝试做

stack<string> st;
string str;
while(str!="n")
{
cin>>str;
if(str == "n")
{
break;
}
st.push(str);
}

看看是否有效。如果没有,请尝试

while ((str = cin.get()) != 'n')

而不是

while(str!="n")