My Input is as below.
3 8 9 3
4 2 4 0 3
5 1 5 9 3 1
0
1 5
As you can see, the first number of each line means the number of how many inputs left in the line.
How can I get all input via scanf? Or please let me know something new.
My Input is as below.
3 8 9 3
4 2 4 0 3
5 1 5 9 3 1
0
1 5
As you can see, the first number of each line means the number of how many inputs left in the line.
How can I get all input via scanf? Or please let me know something new.
As mentioned in the comments, the problem with scanf()
is (among other things) the way it handles the newline character. However, the sscanf()
function (reading from a string) doesn't have this issue! So, depending on exactly what you're trying to achieve, maybe something like the following code will help:
#include <stdio.h>
int main()
{
int a[5], n = 0, given;
char buffer[200];
while (n >= 0) {
printf("\nEnter n and a list of numbers: ");
fgets(buffer, 200, stdin);
printf("Input was: %s", buffer);
n = -1;
given = sscanf(buffer, "%d %d %d %d %d %d", &n, &a[0], &a[1], &a[2], &a[3], &a[4]);
if ((given < 1) || (given != n + 1)) printf("Invalid input!\n");
}
return 0;
}
I'm not saying it's an ideal solution, or even that you could use it, but it may give you some clues as to where to go next.
Let me know how you find it.