Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote a script to understand the map STL better.
I wanted to verify user input was an integer, therefore I used isdigit to check the user input.

The input is an integer, and I am not certain isidigit is the best method to check if user input is an integer.

However, the if statement in which isdigit is being used only validates the variable if the condition is set to false and I do not understand why?

**NOTE: Kindly explain like I am 5.
Using simple objects for example like apples and oranges would be great.

I interpret this as: (expected results)
if(isdigit(x) == true)) {
then move to next step;
}

However, the actual results are:
if(isdigit(x) == false)) {
scripts runs;
}

int main()
{
	map<string, int>num_for_map, sec_num_for_map;

	char x;
	cout << "Enter an integer to map 'Num 1' to: " << flush;
	cin >> x;

	if (isdigit(x) == true) {
		char y;
		cout << "Enter a second integer to map 'Num 2' to: " << flush;
		cin >> y;

		if (isdigit(y) == true) {
			// Map key-value pairs using subscript[] and assignment operator
			num_for_map["Num 1"] = x;
			sec_num_for_map["Num 2"] = y;

			// Traverse through map
			for (auto a : num_for_map) {
				cout << a.first << " --> " << a.second << endl;
			}

			for (auto b : sec_num_for_map) {
				cout << b.first << " --> " << b.second << endl;
			}
		}

	}

	return 0;
}


What I have tried:

I tried setting if statement to true and this did not work.

I have tried using scanf but this also expects a false boolean value which Visual Studio does not like because it raises and error and states this function is not safe, to use scanf_s instead. I did so, with the same result.
Posted
Updated 4-Jul-22 12:22pm

1 solution

Your problem is that your variables x and y are declared as type char. Type char is a single ASCII character, e.g. 'A', or '%' or '7'. So when you do cin >> x; the system reads the first character from the input, and stores that in X. If you enter '7', the ASCII value '7' is stored in x. The character '7' does not have a numerical value of 7, but of 0x37 or 55 decimal. so when num_for_map["Num 1"] gets assigned a value it gets the value 55, not 7.

For starter programs, you should possibly not try to validate your input. If you use
int x;
cin >> x;
your program will assign an integer to x. When you've got a handle on understanding how map<string,int> works, then maybe you can take a look at what happens when you enter 'abcd' instead of a number at your input prompt.
 
Share this answer
 
Comments
CPallini 5-Jul-22 1:59am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900