The purpose of the code is to see how the strings are stored (whether it ends with \n
or \0
).
void print(char*);
int main(void) {
//fscanf block
char *ss;
ss = malloc(sizeof(char)*100);
printf("String for fscanf: ");
fscanf(stdin, "%s", ss);
printf("For fscanf:\n");
print(ss);
//fgets block
char *gs;
gs = malloc(sizeof(char)*100);
printf("String for fgets: ");
fgets(gs, 10, stdin);
printf("For fgets:\n");
print(gs);
free(ss);
free(gs);
}
void print(char* str) {
int done = 0;
for (int i=0; i<100; i++){
if (done == 3) {
break;
}
if (str[i] == '\0') {
printf("Zero: %d\n", i);
done++;
}
if (str[i] == '\n') {
printf("Return: %d\n", i);
done++;
}
}
}
However for some reason, when I put the fscanf block first, it won't stop and req for the fgets string, it just jumps over and outputs:
String for fscanf: Hello
For fscanf:
Zero: 5
Zero: 6
String for fgets: For fgets:
Return: 0
Zero: 1
But when I put the fgets block first it works fine:
String for fgets: Hello
For fgets:
Return: 5
Zero: 6
String for fscanf: Hello
For fscanf:
Zero: 5
Zero: 6
Why does this occur?