Hello, I'm trying to figure out what to use for "accountn" so that the user can only input a number. If they ended up entering a letter instead, they would get something like "error: You must enter a number".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
char main ()
{
int accountn; // account number
cout<<"Please enter your account number: ";
cin>>accountn;
cout<<endl<<"Your account number is: "<<accountn<<endl;
system ("PAUSE");
return 0;
}
The only way I think of is creating a basic Win32 project, hide the window, show the window's console, and in the procedure, only register the 0-9 keys using the WM_KEYDOWN message.
Looks like I somehow found out how to do it by looking at yours. I reversed the if and else statements Can anyone check if there's any flaws with this (besides the system ("PAUSE"))?
#include <iostream>
usingnamespace std;
char main ()
{
int accountn = 'a'; // account number
a:
cout<<"Please enter your account number: ";
cin>>accountn;
if (accountn=='a') // Output Error
{
cout<<endl<<"Invalid account number"<<endl;
system ("PAUSE");
goto a;
}
else
{
cout<<endl<<"Your account number is: "<<accountn<<endl;
system ("PAUSE");
return 0;
}
}
Edit: Looks like I get stuck in a loop if I have it repeat action at "Output Error".
Handling input is a deceitfully complex task, so this question is actually a common one. The simplest and most robust way to do it is to input as a std::string, then parse it using a std::istringstream and checking for errors.
Uh kaz: Yes there is a major flaw with your code. The goto statement. Do. Not. Ever. Use. It. Unless. It. Is. Absolutely. Necessary.Which.It.Is.Not.In.This.Case.And.Probably.In.No.Other.Case.You.Will.Encounter.In.A.Long.Time.