Reputation: 35
I started learning C programming and in this program I am trying to get user input and then a line at a time and decide if it contains non-int characters. I've been trying this method:
scanf("%d", &n);
if (isalpha(n))
{
i = -1;
}
I googled a bit and learned the function isalpha
is good way to do it. However, I'm getting a segmentation fault every time I test the fragment above with non-int characters (letters for example). Any suggestion would be appreciated.
Upvotes: 0
Views: 1527
Reputation: 755064
Given that n
is an integer, we can diagnose that you are reading a value into n
which is not in the range 0..255 plus EOF (normally -1), so that the code for isalpha(n)
is doing something like:
(_magic_array[n]&WEIRD_BITMASK)
and the value of n
is causing it to access memory out of control, hence the segmentation fault.
Since scanf()
:
you can use:
#include <stdio.h>
int main(void)
{
char n = 0;
while (scanf("%c", &n) == 1)
printf("you typed %d\n", n);
return 0;
}
Upvotes: 1
Reputation: 29399
Make sure you have a character buffer to store the value in. Scan it as a string, and then use isalpha()
:
char buffer[32];
sscanf("%32s", buffer);
// loop and check characters...
if(isalpha(buffer[i])) ....
Note the use of %32s
, this is to prevent buffer overflows (32 == size of buffer)
Upvotes: 1
Reputation: 799
I have no idea why you're getting a seg-fault. I'd have to see more of your program.
But using "%d" for scanf will only accept integer values and you'll get "0" for n that isn't an integer and therefore isalpha(n) will always be false and i will never be set to -1.
Perhaps you aren't initializing i and therefore it is never set. If you are referencing it later, that's probably the source of your seg-fault.
Use scanf("%c", &n), like this:
int main(char** argc, int argv) {
char n = 0;
int i = 0;
scanf("%c", &n);
if (isalpha(n)) {
i = -1;
}
printf("you typed %c, i=%d", n, i);
}
Upvotes: 1
Reputation: 38683
The %d
format specifier forces scanf()
to only accept strings of digits. Given anything else, it will fail and leave n
unfilled (and assuming you didn't initialize n
before, it will be filled with garbage).
The crux of the problem is that isalpha()
expects a value between 0 and 255, and has an assertion to enforce it. At least on my VC++ compiler, it causes a crash with an access violation when given an invalid value (in non-debug mode).
To solve this you just have to switch to a %c
format specifier. Converting n
to a char
would also be advisable as that makes your intent of reading a single character clearer.
EDIT: Given your clarifications in the comments, you can leave everything as is and simply check the return value of scanf()
instead of going the isalpha()
route. It returns the number of values read successfully, so when it encounters a non-integer or end of file, it will return 0. E.g.:
int main() {
int n;
while (scanf("%d", &n)) {
printf("Got int: %d\n", n);
}
}
Upvotes: 2