为什么此代码在遇到换行符之前无法正确读取字符串?
Why doesn't this code correctly read strings until encountering a newline?
我正在尝试编写一个程序,该程序读取用户的一堆字符串,然后是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")
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 读取字符串文本输入以创建 2D 矢量
- 罗马数字到阿拉伯语 (vinculum) - 读取字符串中的字符
- C++:从文件中读取字符串和整数,并获得最大数字
- C++,从文件中读取字符串,分段错误
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 如何从内存中读取字符串?
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- 我需要C++读取字符串数组中每个单词的第一个字母
- 读取字符串C++的字符时出错
- 读取字符串直到标志 (C++)
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++输入文件流无法从文件中读取字符串
- 读取字符串字符时出错
- 如何读取<字符串,矢量<对<int,字符串的映射>>>
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- C++ 使用 Strtok 读取字符串字符时出错
- 使用 getline 读取字符串,但每行中都有换行符