Do ... while () repeating the last line twice

The following code breaks the provided string / string into characters. Why does the loop repeat this last line twice? How to fix it?

#include <iostream> #include <vector> #include <sstream> #include <string> using namespace std; int main() { string main, sub; cout << "Enter string: "; getline(cin, main); istringstream iss(main); do { iss >> sub; cout << sub << endl; vector<char> v(sub.begin(), sub.end()); for(int i = 0; i < v.size(); i++) { cout << v[i] << endl; } } while (iss); return 0; } 

Input signal:

Hello World

Output required

Hello
h
e
l
l
about
peace
well
about
g
l
d

Actual output:

Hello
h
e
l
l
about
peace
well
about
g
l
d
peace
well
about
g
l
d

I removed items that are not related to the problem as much as possible

+5
source share
2 answers

In the last run, iss causes failures, so the sub value is not updated, which causes a repetition. One way to see this is to set sub as an empty line at the beginning of the do loop. To avoid such a problem, I would do the following:

 while(iss>>sub){ cout<<sub<<endl; etc } 

In addition, I would like to point out that you can iterate over a string, since it can be considered as char *, so you do not need vector conversion data.

+7
source

The problem is that converting to bool istream only returns false if bit is set or bit is set, but not if the stream is empty. For example, a failed set is set after you try to extract a string from an empty istream. This is why your loop works again: when istream is empty, failbit is not set, only after no line can be extracted in an additional iteration, the failure bit is set and the loop ends. The solution may be to use:

 #include <iostream> #include <vector> #include <sstream> #include <string> using namespace std; int main() { string main, sub; cout << "Enter string: "; getline(cin, main); istringstream iss(main); while(iss >> sub) { cout << sub << endl; vector<char> v(sub.begin(), sub.end()); for(int i = 0; i < v.size(); i++) { cout << v[i] << endl; } } return 0; } 
+3
source

Source: https://habr.com/ru/post/1243075/


All Articles