double input validation??

Nov 24, 2009 at 6:39pm
Hi I have only been working with c++ for a week now so hopefully I don't sound to ignorant. I have been trying to find a way to only allow an end user to enter a 1 or a 2 and if they don't then loop. Here is the direct code that I am trying to adjust to do this.

1
2
3
4
5
6
7
8
9
10
11
12
13
	{
		//GK stands for Gas Kind
		string GK;
		GK = "1";
		cout << "Please type 1 for Leaded or 2 for Unleaded ";
		//GC stands for Gas Choice
		string GC;
		getline(cin, GC);
		cout << "You entered " << GC << "  ";
		system("PAUSE");
		{
			if (GK == GC)
			{
Nov 24, 2009 at 6:43pm
Put a do while loop the getline() to get the input while the input isn't 1 or 2.
Nov 24, 2009 at 7:01pm
ok I am getting closer , but I still have something wrong with the syntax.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	{
		//GK stands for Gas Kind
		string GK;
		GK = "1";
		string GC;
		cout << "Please type 1 for Leaded or 2 for Unleaded ";
		do
		{
			//GC stands for Gas Choice
			getline(cin, GC);
			cout << "You entered " << GC << "  ";
		}
		while((GC !='1')&&(GC !='2'));
		system("PAUSE");
		
		{
			if (GK == GC)
Nov 24, 2009 at 7:08pm
You need double quotes on line 13: "1"
Nov 24, 2009 at 7:26pm
that was it thank you.
Nov 24, 2009 at 7:31pm
If you know GC can only be 1 or 2, you might wanna define it as an integer since this requires less memory and is good practice. Unless ofcourse you're gonna use some string operations in the rest of your program on this GC variable.
Nov 24, 2009 at 7:34pm
actually this is the only time it gets used in the code, it merely tells the program which direction to take next. I haven't used integers yet though, what is the format for that instead of string?
Nov 24, 2009 at 7:38pm
how do I display a user fail statement only if 1 or 2 wasn't selected?
Nov 24, 2009 at 7:51pm
Not quite sure what you mean...I would just use an if statement.
Topic archived. No new replies allowed.