while循环中的迭代在不接受输入的情况下运行和结束
Iteration in while loop runs and ends without taking inputs?
我想根据当前输入拆分字符串并将其存储在result
deque中,然后再次执行此操作while (count-- > 0)
count = 3
输入字符串:abc defghi
while (count-- > 0){
cout << " start of while loop" << endl;
deque<string> result;
string str2;
cin >> str2;
istringstream iss(str2);
for(string s; iss >> s; ){
result.push_back(s);
}
cout << "result.size() " << result.size() << endl;
}
}
问题:结果大小保持为1,while循环自动运行3次
Todo:结果大小应为3
输出:
start of while loop
abc def ghi
result.size() 1
start of while loop
result.size() 1
start of while loop
result.size() 1
我应该能够接受3次输入,但是while循环自动运行3次而不接受输入和结束。为什么会这样?
而不是:
while (count-- > 0){
cout << " start of while loop" << endl;
deque<string> result; // result created inside loop
你想要这个
deque<string> result; // result created outside loop
while (count-- > 0){
cout << " start of while loop" << endl;
否则,每次循环迭代都会重新创建result。
另外,听起来您希望abc def被视为单个输入,但是cin >> str2
读取一个单词,而不是一行。要读取一行,使用getline
代替:
getline(cin,str2);
相关文章:
- 这个c++代码是如何在没有定义函数的情况下运行的
- 您可以在没有线程的情况下同时运行多个 ISR 吗?
- 如何在不丢失输出的情况下杀死/停止终端中正在运行的进程?
- C++项目编译强制使用 /clr 选项,尽管在没有公共语言运行时支持的情况下执行它
- 如果程序在没有 sudo 的情况下运行,gtk_init会导致 ubuntu 16.04 崩溃
- 我可以在不创建项目的情况下在Visual Studio 2019中编译和运行HelloWorld.cpp吗?
- 如何在不闪烁的情况下运行ESP32的单元测试
- 在最坏的情况下试验快速排序.它运行良好,但在最坏的情况下发生未知错误.我想
- 如何在不受其他文件影响的情况下"by itself" Visual Studio 项目中运行C++文件?
- 在运行时,何时完全初始化 std 库才能在不破坏代码的情况下使用它?
- Qt qml - 在没有任何条件的情况下运行一行(while(true))
- 在给定相同的输入的情况下,某些代码怎么可能花费更多时间来运行,这似乎只是因为它处于循环中?
- 函数如何在不这样做的情况下在新线程上运行"as if"?
- 默认情况下,C++ 开关运行时循环
- while 循环是否在设置标志的情况下运行多次?
- 为什么 free 函数不能在 C 数组上运行,而 std::begin 在某些情况下可以在 C++14 中运行?
- 如果在不需要的情况下运行语句
- 在不使用容器或字符串库的情况下,在运行时增加动态数组大小
- VS Code - 如何在不再次构建的情况下运行未更改的 c++ 文件
- 如何在不将其连接到终端的情况下运行'screen',以便我可以在C++ (qt) 应用程序中捕获输出?