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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getting data 1

Status
Not open for further replies.

ecannizzo

Programmer
Sep 19, 2000
213
0
0
US
In my program I am getting data from the user and putting into a struct. I use getch() to validate each character as its inputted. When I use this on character or string fields it works fine, but when I use it on number fields it saves incorrect data. Maybe the ascii value? But I want it to save what the user is inputting.

int ch;

ch = getch()

That's the code I'm using.

Please help.
 
Yes you are comparing the ascii value with a number, you have a couple of options

if(ch >= 0 && ch<=9)

or instead of getch you could use getline... read in the whole line and use strspn with a character set of alphas and numerics

or isalpha combined with atoi

Matt
 
I definitely need to validate it on each character inputted.
So do I need to do this:

int ch;
ch = getch();

if (ch >= 0 && ch <= 9)
save it to struct;

Sorry, I'm new to c and I don't really understand what you are telling me to do?

Thanks.
 
OOPs... please not i meant to type

if(ch >= '0' && ch <= '9')

Matt

 
Thanks Matt. I looked up the atoi function and its helped me. But I do have one that's supposed to be a type double so I tried using atof, but its not working. Any suggestions?

Erica
 
the reason you are having a problem, i would assume, is because as you are reading in the characters one at a time, you are assuming it is an integer.

i assume you first check if it is an alpha-character
second check if it is a number.

if you are including the decimal point as valid for an alpha character your input comes to a halt and you go back to reading in alpha.

you would want to check if ch is a number. if it is set a flag called reading number

int numeric = 0;

if( isalpha(ch))
{
// do what you do with a character
}
else if(ch == '0' || atoi(ch))
{
// do what you do with a number
numeric = 1;
}
else if(ch == '.' && numeric)
{
// decimal point
numeric = 0;

}
else if(ch == '.')
{
// just a period
}

//what ever else you do


I hope this gives you an idea.

Matt


 
You have to pass a *string* to atof(). You can't pass one character.

This would work:

char myHardcodedString[] = &quot;12345.67&quot;;
double d;

int main()
{
d = atof(myHardcodedString);

return 0;
}

This would NOT work:

int main() // Doesn't work
{
char c; // Doesn't work

c = getch(); // Doesn't work
d = atof(c); // Doesn't work
}

Doug Gale
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top