E
Eduardo Olivarez
The following code does not work correctly on my machine. Either one of the
scanf()'s alone work perfectly. However, when they are combined, the second
scanf() call just reads what the first one received as imput, without
taking any keyboard input and then the process terminates prematurely. I
looked through the glibc documentation trying to figure out what was
causing this to no avail, so I started messing around with the code.
Strangely enough, adding a call to getchar() in between the first scanf and
the second printf solves the problem. I have no idea why. Anyone kind
enough to enlighten me as to whats going on?
Non working code (minimized to isolate error):
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STRLEN 100
int main(void) {
int shift;
char *string;
string = (char *) malloc(sizeof(char) * STRLEN);
printf("Input a number: ");
scanf("%d", &shift);
printf("Input a string: ");
scanf("%[^\n]100", string);
printf("%d\n", shift);
printf("%s\n", string);
}
Working code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STRLEN 100
int main(void) {
int shift;
char *string;
string = (char *) malloc(sizeof(char) * STRLEN);
printf("Input a number: ");
scanf("%d", &shift);
getchar();
printf("Input a string: ");
scanf("%[^\n]100", string);
printf("%d\n", shift);
printf("%s\n", string);
}
Output of non working code:
remus@phobos remus $ ./test
Input a number: 12
Input a string: 12
remus@phobos remus $
scanf()'s alone work perfectly. However, when they are combined, the second
scanf() call just reads what the first one received as imput, without
taking any keyboard input and then the process terminates prematurely. I
looked through the glibc documentation trying to figure out what was
causing this to no avail, so I started messing around with the code.
Strangely enough, adding a call to getchar() in between the first scanf and
the second printf solves the problem. I have no idea why. Anyone kind
enough to enlighten me as to whats going on?
Non working code (minimized to isolate error):
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STRLEN 100
int main(void) {
int shift;
char *string;
string = (char *) malloc(sizeof(char) * STRLEN);
printf("Input a number: ");
scanf("%d", &shift);
printf("Input a string: ");
scanf("%[^\n]100", string);
printf("%d\n", shift);
printf("%s\n", string);
}
Working code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STRLEN 100
int main(void) {
int shift;
char *string;
string = (char *) malloc(sizeof(char) * STRLEN);
printf("Input a number: ");
scanf("%d", &shift);
getchar();
printf("Input a string: ");
scanf("%[^\n]100", string);
printf("%d\n", shift);
printf("%s\n", string);
}
Output of non working code:
remus@phobos remus $ ./test
Input a number: 12
Input a string: 12
remus@phobos remus $