I'm new at C and I'm having some issues with my code. I'm trying to do a loop to read every input from a user, until he press ENTER and get out of the loop to execute other functions. Here's my code:
int main(char argc,char *argv[]){
char input[200];
char *epc;
int err = 0;
int idt = 0;
while (fgets(input,200,stdin) != NULL){
epc = strchr(input, ' ');
idt = epc[2] - '0';
if(idt == 1){
err++;
}
}
}
printf("Success");
return 0;
}
So basically if someone enters 5 01, it should go through the loop, and then if the user enters again nothing by pressing the ENTER key, it should break out of the loop and print Success.
Except it doesn't work and I'm getting a segmentation fault in the terminal every time.
If I do it with an artificial loop, example while(i<3) and i++ at the end of the loop to break, it does work.
Can you help me out please?
The flaw is that you expect fgets
to return NULL
if the user presses just ENTER, but that's not what happens. In that case, fgets
returns just the newline, so input
is the string "\n". Then strchr
tries to find a space in the string "\n" but there is none, so it returns NULL
and then espace[2]
dereferences NULL
causing the segfault.
If you want the loop to break upon user pressing just ENTER, then you'll need to test for getting the string "\n". You could do something like
while (fgets(input,100,stdin) != NULL){
if(input[0] == '\n'){
break;
}
Also note that there are other inputs that would cause problem. Anything where the first space has less than 2 characters following it, (such as "0 1") will cause espace[2]
to index to the string terminator or beyond.