tags:

views:

2437

answers:

5

I am using fscanf to read a file which has lines like
Number <-whitespace-> string <-whitespace-> optional_3rd_column

I wish to extract the number and string out of each column, but ignore the 3rd_column if it exists

Example Data:
12 foo something
03 bar
24 something #randomcomment

I would want to extract 12,foo; 03,bar; 24, something while ignoring "something" and "#randomcomment"

I currently have something like

while(scanf("%d %s %*s",&num,&word)>=2)
{ 
assign stuff 
}

However this does not work with lines with no 3rd column. How can I make it ignore everything after the 2nd string?

+2  A: 

Use fgets() to read a line at a time and then use sscanf() to look for the two columns you are interested in, more robust and you don't have to do anything special to ignore trailing data.

Robert Gamble
yes.. but i am currently using the number of items scanf matched >=2 to detect the valid portion of the file...... it would be great if i could integrate the process within the scanf itself so as to keep the while loop condition intact
adi92
Robert Gamble
A: 

I often use gets() followed by an sscanf() on the string you just, er, gots.

Bonus: you can separate the test for end-of-input from the parsing.

Adam Liss
I hope you are joking about using gets().
Robert Gamble
+3  A: 

It would appear to me that the simplest solution is to scanf("%d %s", &num, &word) and then fgets() to eat the rest of the line.

Artelius
+2  A: 
Adam Rosenfield
A: 

Bit of a question dodge, but this trick with the format identifier star %*s really helped me out as I've got a constant 3rd column. But, does anyone know where I can find out about it? I've no idea where it's from or what it does, but I guess it's just another part of the format specifiers that in some way allows scanf to scan then forget the value...?

Tommo
Best asked as a separate question, but check `man scanf`.
Scott Wales