Hi,
I am trying to use sscanf() inside a for() loop to read integers into an array, as shown below.
Code:
char numString[100]; /* Numbers supplied by user. */
int number[6] = { 0, 0, 0, 0, 0, 0 };
/* Prompt user for input values. */
printf("Enter a series of six numbers:\n");
/* Capture user number string. */
fgets(numString, sizeof(numString), stdin);
/* Convert digit string to number and store in array. */
for (int i = 0; i < 6; ++i)
{
sscanf(numString, "%d", &number[i]);
}
for (int i = 0; i < 6; i++)
{
printf("The number is %d\n", number[i]);
}
When I run the above code I get the following output
Enter a series of six numbers:
123 -254 -300 4096 5 -60000
The number is 123
The number is 123
The number is 123
The number is 123
The number is 123
The number is 123
From the above output it would seem that each call to sscanf() in the first for() loop causes sscanf() to start reading from the beginning of the number string entered by the user.
My problem is that I don't understand how to get sscanf() in the first for() loop to advance to the next digit string within the input string. For example, to move from reading 123 to reading -254, and so on. I have(!) done a web search but cannot find anything relating to this particular problem.
(I know that reading integers into an array can be done using scanf() but I remember reading somewhere that scanf() was either not secure or buggy and so should not be used.)
Could some kind soul please provide (or point me towards) a text description of how I can get sscanf() to do this advancing ?
Best regards,
Stuart