Stringstream doesn't pass value (skipping?)

I got this problem once but with std::cin. Down below is my program. And the input is:
4
1 4 3 2
5
2 3 4 5 1
1
1
0
The problem was at line 24, the while-loop looped once that means the stringstream had just received the value "2 3 4 5 1".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

int main() {
	while (true) {
		bool ambi = false;
		int n, in;
		string s;
		getline(cin, s);
		stringstream ss(s);
		ss >> n;
		if (n == 0) break;

		vector<int> num(n);
		getline(cin, s); //s was "2 3 4 5 1" after this
		ss.str(s); // ss' stream was "2 3 4 5 1"
		for (int i = 1; i < n + 1; i++) {
			ss >> in; //AFTER THIS: in wasn't passed the value 2
			//in != 2
			//in == 0
			if (in != i + 1 || (i == n && in != 1)) {
				ambi = true;
				break;
			}
		}

		switch (ambi) {
		case true: cout << "ambiguous\n";
			break;
		case false: cout << "not ambiguous\n";
			break;
		}
	}

	return 0;
}


Need a solution, please!!!
I don't know what your requirements are, but if you just want to read in the numbers, you don't nead getline/stringstream and all that stuff.
1
2
3
4
5
6
7
8
9
#include <iostream>

int main()
{
    int num;
    while (std::cin >> num)
        std::cout << ' ' << num;
    std::cout << std::endl;
}
Last edited on
Let me explain it to you. Here if I replace all the getlines/stringstreams with cin. After the while-loop (at line 9) did everything in it (until line 36), it went back to the 9th line so as to do everything again. Until line 16, n equaled 0 then, after line 16, n should be assigned to any value we entered then, of course but it wasn't. That's the problem. Debug the program and you'll see.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

int main() {
	while (true) { //<--- LINE 9: while loop
		bool ambi = false;
		int n = 0, in;
		/*string s;
		getline(cin, s);
		stringstream ss(s);
		ss >> n;*/
		cin >> n; // <--- LINE 16
		if (n == 0) break;

		vector<int> num(n);
		/*getline(cin, s);
		ss.str(s);*/
		for (int i = 1; i < n + 1; i++) {
			cin >> in;
			if (in != i + 1 || (i == n && in != 1)) {
				ambi = true;
				break;
			}
		}

		switch (ambi) {
		case true: cout << "ambiguous\n";
			break;
		case false: cout << "not ambiguous\n";
			break;
		}
	} //<--- LINE 36: end while loop

	return 0;
} 
Topic archived. No new replies allowed.