Hi all,
I am trying to make sure that users can only input integers in my program and no other types. Here is the program:

#include<iostream>

using namespace std;

int main()
{

int numbers[9];
int k;

cout<<"Enter 9 numbers: ";

for( k = 0; k<9; k++)
{
cin >> numbers[k];
}
cout<<"here are your numbers: ";
for (k=0; k<9; k++)
{
cout<<" "<<numbers[k];
}

}

I am having real trouble (I am still a beginner) to validate user input.
I have tried with the

isdigit()

function, with if

((numbers[k]<'48' || numbers[k]>'58'))

because I thought that the ascii table would have been of use but no joy. All the above included in a while loop of course...

I meant I tried things like:

while((numbers[k]<'48' || numbers[k]>'58'))
	{
		cout<<"wrong, again ";
			cin >> numbers[k];
	}

or

while((!isdigit(numbers[k]))
	{
		cout<<"wrong, again ";
			cin >> numbers[k];
	}

Any suggestion?
thanks

The easoest way to validate that all input only contains digits it to get the input as a string instead of an integer. Then you can easily determine if it contains any non-digit characters without screwing up the entire input stream.

>>while((!isdigit(numbers[k]))
Useless loop because numbers can not hold anything other than digits. And cin will not let you enter anything other than digits in numeric variables.

hi ya,
thanks.
DO you mean something like

#include<iostream>

 
using namespace std;
 
int main()
{
 
char numbers[5];
int k;
 
cout<<"Enter 5 numbers: ";
 
for( k = 0; k<5; k++)
{
cin >> numbers[k];
while((numbers[k]<46) || (numbers[k]>58))
	{
		cout<<"wrong, again ";
		cin >> numbers[k];
	}
}
cout<<"here are your numbers: ";
for (k=0; k<9; k++)
{
cout<<" "<<numbers[k];
}
 
}

I mean something like this:

int main()
{
   std::string number;
   cout << "Enter 5 digits\n";
   cin >> number;
   for(int i = 0; i < number.length(); i++)
   {
     if( !isdigit(number[i]) )
     {
        cout << "You idot!  Numeric digits only!;
        break;
     }
   }
}

oh I see, it makes sense yes thanks. But what if I want to keep the int array? Do you think i could do that and maybe use a cast construct? Or is it not an option?

After the validation you cn convert the string to an integer if you want to.

#include <sstring>
...
<snip>
int n;
stringstream s;
s << number;
s >> n;
cou << n << '\n';

Unless you are instructed to do so there is no reason to put each digit of the string in its own int variable. But you could do that too

int n[5];
for(int i = 0; i < number.length(); i++)
   n[i] = number[i] - '0'; // convert ascii digit to binary

I see, thanks for your help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.