Reputation: 31
I am really new to C and I am facing a problem with fgets(). I need to make multiple calls to fgets in order to retrieve 4 pieces of data, a name, age, num1 and num2. I cannot use scanf for this I have to use fgets. However, I am facing problems when I make multiple calls to fgets. And just to clarify I want to read num1
and num2
as strings. Here is my code:
int main(int argc, char const *argv[])
{
/* code */
char name[50];
char ageString[3];
char num1[6];
char num2[6];
printf("Enter your name: ");
fgets(name, 50, stdin);
printf("Enter an age: ");
fgets(ageString, 3, stdin);
printf("Enter num 1: ");
fgets(num1, 6, stdin);
printf("Enter num 2: ");
fgets(num2, 6, stdin);
// replace the trailing '\n' with '\0'
name[strcspn(name, "\n")] = '\0';
ageString[strcspn(ageString, "\n")] = '\0';
num1[strcspn(num1, "\n")] = '\0';
num2[strcspn(num2, "\n")] = '\0';
printf("Your name is: %s, you are %s years old, num1: %s, num2: %s\n", name, ageString, num1, num2);
return 0;
}
Here is what I get outputted in the terminal:
Enter your name: Random
Enter an age: 21
Enter num 1: Enter num 2: 1
Your name is: Random, you are 21 years old, num1: , num2: 1
The program reads name and age fine but the num1 is not being read and the formatting is really off.
If anyone has a fix for this that would be greatly appreciated. Again, I am very new to C so I am still learning.
Thank you!
Upvotes: 2
Views: 612
Reputation: 682
The problem is that your array sizes are too small. When you type in "21\n" and fgets
is called with 3 as the size, it reads 2 characters (not 3) The \n remains, so fgets
next reads only the newline. The solution would be to to increase your array size by one (for that specific input) or "Don't skimp on Buffer Size...." (@David C. Rankin)
Upvotes: 2