[Solved] C String Error – Need to understand code [closed]


This is the same thing I talked about recently here: D lang – Using read and readln() in the same program although in C instead of D so the solution is slightly different but same explanation.

The scanf stops on whitespace, which is a newline… which gets sees as the end of input and thus reads an empty line.

The solution is to consume that newline before continuing:

printf("how many slices of %s of pizza \n",topping);
scanf("%d",&slices);
fgetc(stdin); // ADDED THIS LINE TO READ PAST THE NEW LINE CHARACTER
printf("which is your favorite hotel in town?\n");
gets(hotel);

PS don’t use gets, use fgets(hotel, 50, stdin); instead. The 50 there is the size of the buffer, ensuring it doesn’t overflow.

4

solved C String Error – Need to understand code [closed]