Reputation: 29176
I want to read some numbers from the console. The numbers will appear in this way -
5 1 2 3 4 5
4 5 6 7 8
6 2 3 4 5 6 7
..............
EOF
The starting number represents how many number will appear in that line, i.e., the first number of the first line is 5, so there will be 5 more numbers on this line. The end of input will be denoted by the EOF (end-of-file).
I thought of reading the whole line as a string and then convert them to numbers but I want to know is there any other way to do this.
Upvotes: 1
Views: 277
Reputation: 754910
The 'standard' answer is scanf()
. The trouble with the standard answer is that it won't allow you to check that there are the correct number of numbers on a line. So, your idea of reading a line and then converting it piecemeal is much better for error detection.
Take a look at How to use sscanf() in loops; the answer there shows you the basics of what you should do. It isn't an exact duplicate. You will read a first value identifying how many entries are on the line, followed by code to read that many entries into an array, with appropriate diagnostics if the data doesn't match the format claimed for it.
If you are in charge of the data format, you should consider dropping the count field - let the computer count how many values are on the line. Computers are good at counting, and it removes a source of errors to be detected and handled (so it makes the programming easier). (If you do change the input format, your question becomes a duplicate of the linked question.)
Upvotes: 3
Reputation:
Have a look at the documentation of scanf
:
int count, current, i;
while(scanf("%d", &count) > 0)
{
for(i = 0; i < count; i++)
{
scanf("%d", ¤t);
// store current
}
}
Upvotes: 2