I want to fill an array with int values which are extracted from a buffer. I want to do something like:
char buffer[BUFF_MAX];
int numbers[NUM_MAX];
int i = 0;
fgets(buffer, BUFF_MAX, stdin);
while(sscanf(buffer, "%d", &numbers[i]) == 1)
{
++i;
}
but I am having all kinds of problems using this method. Perhaps it has something to do with the \n in the buffer? It seems like the same value is assigned to every element and if I type in anything greater than around 130, a garbage value is stored.
The user will be typing in something like:
12 543 5 234 9
and I want these values to be stored in numbers[] as 5 different elements. There will be different amounts of numbers in the buffer each time (depending on what the user types in).
You can find out where
sscanf()got to in parsing the string by using the%nconversion specifier, thus:Testing
Input string:
Output:
The
%nmodifier was added in C89, but not many people know that it is there. It also ‘works’ in theprintf()family of functions, but is even more lethal there because people aren’t used to seeing output parameters in aprintf()format string. At least withscanf()et al, you are expecting inputs.Beware of ‘format string vulnerabilities’, a decent search term to use in your favourite search engine. You should be beware of them, independently of this question.
[Updated to check that
fgets()does not indicate an error or EOF. Always check that read operations do what you expected. Well, almost always — if you’re recovering from an error and don’t care what is read because you won’t be using it, maybe you don’t need to check. If you’re going to use the read data, you should check that you actually got the data to work with.]