Issue
I have a problem when getting input from the user. I used the scanf
function to get the input from the user, which I think is the cause of the problem.
I want the two prompts to be on separate lines.
The following code is a simple example of the problem:
#include <stdio.h>
int main(void)
{
char name[20];
int age = 0;
int index;
printf("1- Insert a new student.\n");
printf("2- Delete a student.\n");
printf("3- Show all students.\n");
printf("4- Exit.\n\nChoose: ");
scanf("%d", &index);
printf("Enter your name: ");
scanf("%20[^\n]s", name);
//fgets(name, 20, stdin); // <--- Does the same thing.
printf("Enter your age: ");
scanf("%d", &age);
printf("Name: %s, Age: %d\n", name, age);
return 0;
}
The result as text:
1- Insert a new student.
2- Delete a student.
3- Show all students.
4- Exit.
Choose: 2
Enter your name: Enter your age:
An image:
Why did the two prompts show on the same line?
Solution
I suggest you change this:
scanf("%20[^\n]s", name);
to this:
scanf(" %19[^\n]", name);
for these reasons:
The buffer size you specify to
scanf
does not include the finalNUL
terminator (unlike withfgets
).The previous
scanf
left a newline in the input buffer, and the format specifiers%[]
and%c
do not automatically filter it (unlike%d
and other specifiers). Adding the space tellsscanf
to filter it.The final
s
is not part of the format%[]
but is a frequent mistake by coders who have used%s
.
Note too, that scanf
with %[]
is not equivalent to fgets()
, which reads any final newline and places it in the buffer supplied.
Answered By - Weather Vane