I am currently working on a project where the user is to enter how many employees, the employee ID number, name, wage per hour, and hours worked. Currently have a working version that does not check whether or not the user entered a numerical value or a character value into the input stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
do
{
//Get the user input of how many employees there are
cout<<"\nHow many employees are there? ";
cin.getline(ctemp,4,'\n');
inum=atoi(ctemp);
clearbuf();
//for(i=0; i<ctemp.strlength(); i++)
//{
if (!isdigit(ctemp[0]))
// j+=1;
// }
// if (j>0)
cout<<"\nERROR! Please enter a number."<<endl;
}while (!isdigit(ctemp[0]));
What I would like to do is use the for loop to check each input value in the char variable ctemp[] as either numeric or alpha. When i have my code as seen above, it works fine. When I try to sub !isdigit(ctemp[0]) with either j or inum, I have the problem of infinite loop. Also, could someone please explain why I get the Error: Expression must have class type when I uncomment the for loop. The error is on ctemp. It is clearly defined and usable everywhere else in my code. Any help will be greatly appreciated! Thanks in advance.
ctemp is a char array, it does not have a method called strlength().
You need to change for(i=0; i<ctemp.strlength(); i++)
to for(i=0; i < strlen(ctemp); i++)
do
{
//Get the user input of how many employees there are
cout<<"\nHow many employees are there? ";
cin.getline(ctemp,4,'\n');
inum=atoi(ctemp);
clearbuf();
if (!isnumeric(ctemp))
cout<<"\nERROR! Please enter a number."<<endl;
}while (!isnumeric(ctemp));
(It would be better to store result of isnumeric() in a variable to avoid repeated call)
Thank you both andywestken and binarybob350, that helped immensely. You are right andywestken, it does make sense to make a function. I had at first made the function, but couldn't get it to work, so I put what I had posted into the main function to try to debug. Now that it is working, I can use the function to check for numeric or alpha (in it's own function) for all five user inputs. Thanks again guys.