Reputation: 510
I want to split string and store it in result
deque according to current input and do this again while (count-- > 0)
count = 3 in this case.
input string : abc def ghi
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;
}
}
Problem : result size remains 1 and while loop runs 3 times automatically.
Todo : result size should be 3 in 1 iteration
Output :
start of while loop
abc def ghi
result.size() 1
start of while loop
result.size() 1
start of while loop
result.size() 1
I should have been able to take inputs 3 times, but while loop runs 3 time automatically without taking inputs and ends. Why is it happening ?
Upvotes: 1
Views: 42
Reputation: 64308
Instead of this:
while (count-- > 0){
cout << " start of while loop" << endl;
deque<string> result; // result created inside loop
you want this
deque<string> result; // result created outside loop
while (count-- > 0){
cout << " start of while loop" << endl;
otherwise, result is being recreated for each iteration of the loop.
Also, it sounds like you are expecting abc def ghi to be treated a single input, but cin >> str2
reads one word, not one line. To read a line, use getline
instead:
getline(cin,str2);
Upvotes: 3