reading nth columns

T

Tagore

hi,

How can I read nth column of a file.

e.g suppose format of my file is something like

Setra 40 5.0 90
Ram 50 6.4 50
Tom 45 2.3 45
.....

Now I want to read 3rd column values i.e. 5.0, 6.4, 2.3,......

I know of fscanf which can be used like
fscanf(fp,"%s %d %d ",&a,&b,&c)

but I want to read only 3rd column. How can I do this?

thanks,
 
K

Keith Thompson

Eric Sosman said:
Tagore said:
How can I read nth column of a file.

e.g suppose format of my file is something like

Setra 40 5.0 90
Ram 50 6.4 50
Tom 45 2.3 45
....

Now I want to read 3rd column values i.e. 5.0, 6.4, 2.3,......

I know of fscanf which can be used like
fscanf(fp,"%s %d %d ",&a,&b,&c)

but I want to read only 3rd column. How can I do this?

You could use the assignment-suppression flag:

fscanf(fp, "%*s %*d %d", &c);

(Two minor points: First, the `&a' in your example is probably
wrong. Second, the white space between the conversion specifiers
is harmless but unnecessary; "%s%d%d" and "%*s%*d%d" would have
the same effect as the format strings shown.)

(Two not-so-minor points: Third, if you don't check the value
returned by fscanf() you'll have no way to know whether you
succeeded in reading anything. Fourth, if your data is really
line-oriented you're probably better off reading the whole line
into a char[] array and using sscanf() on the array; if you choose
to stick with fscanf() you'll need to do something to skip over
the un-read stuff that follows the third column.)

Fifth, if you use "%d" to read "6.4", you'll get the value 6.
You want "%f" for floating-point.

Sixth, either fscanf or sscanf invokes undefined behavior if you
attempt to read a number that's outside the range of the target type
(C99 7.19.6.2p10, last sentence). You can use one of the strto*()
functions for greater safety.
 
J

Jens Thoms Toerring

Eric Sosman said:
You could use the assignment-suppression flag:

fscanf(fp, "%*s %*d %d", &c);

Minor nitpick: since in the third column there is a floating point
value and because there is another int in the fourth, also to be
skipped, this probably should be either

fscanf(fp, "%*s%*d%f%*d", &c);

fscanf(fp, "%*s%*d%lf%*d", &c);

(and 'c' should be a variable of either a float or double type).

Regards, Jens
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top