Matheus Dutra Matheus Dutra - 3 months ago 24
C Question

Scanf repeats itself in C

This is a simple program in which the user enters a series of numbers which are then added. The result is printed on the screen. Here's the code:

int main() {
int * numbers;
int result = 0;
int howMany;
int i;

printf("How many numbers would you like to add?\n");
scanf(" %d\n", &howMany);

numbers = (int *) malloc(howMany * sizeof(int));

for(i = 0; i < howMany; i++){
printf("Please enter number %d.\n", i + 1);
scanf(" %d\n", &numbers[i]);
result = result + numbers [i];
}
printf("Result: %d", result);
return 0;
}


But there is a problem. The program asks for how many numbers the user would like to add twice for some reason. Why is that? How can I fix it?
Also, not sure if this is related but the results also make no sense. Sometimes they are correct, other times they aren't, not sure why either.
Thanks.

Answer

The program asks for how many numbers the user would like to add twice for some reason. Why is that? How can I fix it?

Your program prompts me only once for how many numbers. It does, however, defer asking for each specific number until after I enter it, and then it requires an extra non-blank line after the last (late) prompt before it outputs the result.

Also, not sure if this is related but the results also make no sense. Sometimes they are correct, other times they aren't, not sure why either.

It is related: the fact that the per-number prompts are late is confusing you about which numbers are being added.

This all comes down to your scanf() formats, as @Mark already remarked (albeit somewhat tersely). Any nonempty run of whitespace, including newlines, in a scanf() format matches a possibly-empty run of whitespace. When it is matching such a run, scanf() has to keep scanning until it sees a non-whitespace character. Interactive input is line-buffered, however, so no new input is available to it until you send a whole new line. Then the first non-whitespace character on that next line is ready and waiting for the following scanf().

scanf() can be quite tricky to use correctly, especially for interactive input. It is best suited for fixed-format input. You can do this with scanf() -- @Mark showed you how -- but the usual recommendation around here is to use fgets() to read input one line at a time, and sscanf() (or your choice of other mechanism) to parse each line. Even that can be a challenge to make bullet-proof, but you start out on firmer footing.

Comments