Benjamin
Benjamin

Reputation: 3

Reading an unknown number of values from standard input in C

I need to read an input file like this:

0.142857 0.714286 
0.642857 0.714286 
0.285714 0.500000
0.500000 0.500000 
0.785714 0.428571 
0.357143 0.357143 
0.714286 0.214286 
0.928571 0.071429

Each line corresponds to a point on a plane, with an unknown number of points input comes from standard input..

any ideas?

Upvotes: 0

Views: 942

Answers (3)

user142162
user142162

Reputation:

scanf returns the number of parameters is receives. You can test to make sure you're getting what you're asking for.

Example:

#include <stdio.h>

// ...

double f1, f2;

while(scanf("%lf %lf", &f1, &f2) == 2)
{
  // store f1 and f2 somewhere
}

Upvotes: 3

pmg
pmg

Reputation: 108938

If you trust the input enough, use scanf().

Verify the return value to make sure a pair was read, test for EOF and you're all set.

double x, y;
while (scanf("%lf%lf", &x, &y) == 2) {
  /* deal with (x, y) */
}
if (!feof(stdin)) /* input error */;

NOT TESTED


If you don't trust the input, use fgets() and parse each line "by-hand"

Upvotes: 1

Argote
Argote

Reputation: 2155

Read each pair and add it to a Linked List until you get all pairs in the input?

Upvotes: 0

Related Questions