I'm a first year Computer Science student learning C programming. I'm trying to write a simple program that asks the user for their roll number (an integer) and then their name (a string).
However, after I input the roll number, the program seems to skip the input for the name and immediately prints the output.
Here is my current code:
#include
int main()
{
int rollNumber;
char studentName[50];
// 1. Get Integer Input
printf("Enter your Roll Number: ");
scanf("%d", &rollNumber);
// 2. Get String Input
printf("Enter your Full Name: ");
// PROBLEM IS HERE: The program skips this scanf call.
scanf("%s", studentName);
// 3. Print Output
printf("\n--- Student Info ---\n");
printf("Roll Number: %d\n", rollNumber);
printf("Name: %s\n", studentName);
return 0;
}
Example Output when I run it:
Enter your Full Name:
--- Student Info ---
Roll Number: 101
Name:
My Questions:
What is the specific reason the second scanf (for the string) is being skipped? Is it related to how the first scanf handles the Enter key?
What is the best way to fix this in C? Should I use an extra getchar(), or is there a specific format specifier I should use in scanf (e.g., " \%s" with a space)?
If I wanted to allow the user to enter a name with spaces (e.g., "John Doe"), what would be the recommended function or method to use instead of scanf(" \%s", ...)?
I'm looking for an explanation that helps me understand how scanf handles the input buffer.