Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how do I check to see if user entered a string when integers are asked

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
If i have a user enter 3 integers, how do I check to make sure that they did use only integers and not characters or strings...
 
You could probaly use.

char string[3] = "123";
bool number1;
bool number2;
bool number3;

if(string[0] = '0' || string[0] = '1' || string[0] = '2' || string[0] = '3' || string[0] = '4' || string[0] = '5' || string[0] = '6' || string[0] = '7' || string[0] = '8' || string[0] = '9')
{
number1 = true;
}

if(string[1] = '0' || string[1] = '1' || string[1] = '2' || string[1] = '3' || string[1] = '4' || string[1] = '5' || string[1] = '6' || string[1] = '7' || string[1] = '8' || string[1] = '9')
{
number2 = true;
}

if(string[2] = '0' || string[2] = '1' || string[2] = '2' || string[2] = '3' || string[2] = '4' || string[2] = '5' || string[2] = '6' || string[2] = '7' || string[2] = '8' || string[2] = '9')
{
number3 = true;
}

if(number1 && number 2 && number 3)
{
//place your code here
}

there's probaly a easy'er way to do this, but it is a solution I hope you can use it!

..:::GOOOD:::..
 
The previous link is from the 'C' Forum,i think that you might find the explanation of what you are looking for in it.
 
Sorry it was the wong link this one is the right one:
Thread205-196473
 
The easiest way would be to read into a character array and convert the value using atoi. To make sure it is all integers you would use strspn


char buffer[32];
cout<<enter a number;
cin>>buffer

if(strspn(buffer,&quot;1234567890&quot;) == strlen(buffer))
{
// valid
}


<Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top