0

can any1 pls tell me how can i solve my problem?
i'm running a c program that required the user to key in a int, but instead of keying in int the user key in char... and somehow the program stor the char n turn it into int...
some even continue looping... how can i solve it... demanding for help...

4
Contributors
6
Replies
8
Views
6 Years
Discussion Span
Last Post by thekashyap
0

char is in fact a (very small) integer type. To convert the string of char to int, use atoi() or something similar.

0

char is in fact a (very small) integer type. To convert the string of char to int, use atoi() or something similar.

sorry but how to use the atoi() as i'm a new in this c programming...

i've tried to limit it with the if else but it just work in simple function but not in the complete main

1

You must first read in your text book how to code in C. This is not a good place to learn the very most basic things, but a place to come if you have written a program that is not working right, or maybe does not compile.

0

If you want to prevent someone from entering anything other than numeric digits I would get then to enter a string instead of int, then check the string for digits.

char input[255] = {0}; // input buffer
char *ptr;
printf("Enter a number\n");
fgets(input,sizeof(input),stdin); // get keyboard 
// now strip off the trailing '\n' that fgets() add to the end of the string
ptr = strrchr(input,'\n');
if( ptr != NULL)
   *ptr = '\0';
// now check each character for digits. 
// If any non-digits are found then loop 
// back to the top of this code and to it again
0

char is in fact a (very small) integer type. To convert the string of char to int, use atoi() or something similar.

From atoi(3)
"
DESCRIPTION
The atoi() function converts the initial portion of the string pointed to by nptr
to int. The behaviour is the same as

strtol(nptr, (char **)NULL, 10);

except that atoi() does not detect errors.

"

So as you recommended, "something similar" (strtol) is better than atoi(). Especially given that OP wants to find errors.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.