Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So i have this 2D array that can receive input from the user, as of now getting integer works perfectly fine , but i need it to be able to receive characters as well

std::cout << "Enter the values : " << endl;
                int value = 0;
				cin >> value;
				
				if (std::isdigit(value)) 
				{
					matrix[x][y] = value;
				}
				else 
				{
					matrix[x][y] = 0;
				}


What I have tried:

i tried using the simple isDigit function but when i enter anything else than an integer it terminates the whole program and yes the objective is to equal value to = 0, might be basic but im new to c++
Posted
Updated 7-Oct-22 6:17am
Comments
jeron1 7-Oct-22 12:17pm    
isdigit() is looking for a character type, try changing 'value' and 'matrix' (I am guessing matrix type is int) to be type char, and see what happens.

To do that, you need to change it round: read a string value, and see if you can convert it to an integer. If you can, use the number. If it isn't - its character based. Use stoi[^] in a try ... catch block.
 
Share this answer
 
You need to change the declaration of value to char. That way you can accept either type. Note that your code above will never work since std::isdigit tests characters, not integer values. So you need something like:
C++
std::cout << "Enter the values : " << endl;
char value;
cin >> value;

if (std::isdigit(value)) 
{
	matrix[x][y] = value - '0'; // convert character to integer
}
else 
{
	matrix[x][y] = 0;
}
 
Share this answer
 

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