Reputation: 667
I am writing a simple code where I need to input a number n, followed by n strings in the format "string int" (eg. hello 100). I have used fgets()
function to take the string input. The code seems to be working fine for all iterations except the first one. The first iteration seems to have an empty input for cmd, but the rest of the iterations runs fine. I've tried various functions like scanf()
and gets()
, but the problem remains. Can anyone please point out the problem?
#include <stdio.h>
#include <stdlib.h>
int main() {
int num_msg, i;
printf("Hello, How many strings should I read?: ");
scanf("%d", &num_msg);
for (i = 0; i < num_msg; i++) {
int child;
char cmd[100], msg[100];
printf("Message %d (<msg> <int>):", i + 1);
if (fgets(cmd, sizeof(cmd), stdin)) {
//printf("cmd %s\n", cmd);
sscanf(cmd, "%s %d %*s", msg, &child); //separates string and int
printf("%s %d \n", msg, child); //prints them
}
}
}
Upvotes: 0
Views: 1806
Reputation: 145287
You need to consume the \n
that follows the number read by scanf()
.
Adding a \n
at the end of the scanf()
format is not appropriate, since it would consume all whitespace characters and keep requesting input until a non space character in input.
A quick and dirty way to do this is to replace the scanf
with:
scanf("%d%*c", &num_msg);
The %*c
reads a single character and does not store it.
You could also store it into a char
variable and verify that it is indeed a '\n'
.
A generic way to ignore all characters upto and including the linefeed:
scanf("%d", &num_msg);
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
You should also check the return value of scanf
to verify that a number was correctly converted.
Upvotes: 4