我想根据当前输入拆分字符串并将其存储在 map_tree( t => t+n)(t)
deque中,然后再次执行此操作result
count = 3.
输入字符串: abc def ghi
while (count-- > 0)
问题:结果大小保持为1,而循环自动运行3次。
Todo :结果大小应为3合1迭代
输出
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;
}
}
我本来应该能够输入3次,但是循环会自动运行3次而不需要输入和结束。 为什么会这样?
答案 0 :(得分: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;
否则,将为循环的每次迭代重新创建结果。
此外,听起来你期望abc def ghi被视为单个输入,但cin >> str2
读取一个单词,而不是一行。要阅读一行,请改用getline
:
getline(cin,str2);