Testing for user input

At the moment if I enter a string first, and something that's not an int second it will just end up in an infinite loop running the else statement.
How do I solve this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main(){
	vector<string> names;
	vector<int> scores;
	string str;
	int num;

	cout << "Enter a name and a score: " << endl;
	while (!(cin >> str >> num && str == "NoName" && num == 0)) {
		if (!(find(names.begin(), names.end(), str) != names.end())) {
			names.push_back(str);
			scores.push_back(num);
			cout << "Enter 'NoName 0' to quit, or continue with names and scores" << endl;
		}
                else {
			cout << "You entered a name that's already there" << endl;
		}
	}
}
If you also posted your #includes along with the rest of the code above main, it would allow to run your code without any modifications, making life easier for all of us.

When you attempt to put a non-number into an int, the cin stream state will become invalid.
To fix this, you need to (1) clear the state of the cin stream, and (2) discard any input remaining in the cin buffer so that you can begin anew.

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

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <limits>

using namespace std;

int main(){
	vector<string> names;
	vector<int> scores;
	string str;
	int num;

	std::string prompt = "Enter a name and a score: ";
	cout << prompt;
	while (!(cin >> str >> num && str == "NoName" && num == 0)) {
		
		if (!cin)
		{
			std::cin.clear();
			std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
			cout << "Invalid input. " << prompt;
		}
		else if (!(find(names.begin(), names.end(), str) != names.end())) {
			names.push_back(str);
			scores.push_back(num);
			cout << "Enter 'NoName 0' to quit, or continue with names and scores: ";
		}
		else {
			cout << "You entered a name that's already there" << endl;
			cout << prompt;
		}
	}
}
Last edited on
Oh okay, sorry..
Thanks a lot!
Topic archived. No new replies allowed.