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...

Recommended Answers

All 6 Replies

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

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

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.

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

thanks for that... already got it now... ^_^

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.

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.