dpalma
dpalma

Reputation: 510

Using sscanf for reading data separated by |

I have to read data from a .txt file, this is a sample of the data:

1 |    SMAX 0.3848 | 0.234 | 0.15

I am only interested on reading the first, third and fourth column (so I want to discard that weird SMAX 0.3848). So far I have this:

while(fgets(buffer, BUFFER_SIZE, fp) != NULL)
{
    sscanf(buffer, "%d | %*s | %lf | %lf", &id, &ra, &dec);
}

However it does not work, I think it is because of the "SMAX 0.3848", and I am incorrectly discarding it. My question is, how could I read this data?

Note: There are many columns in my dataset, and there are other "weird data" that I will need to discard.

Best regards.

Upvotes: 0

Views: 43

Answers (3)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

The problem is the "%*s" it stops scanning when it finds a white space, try this1

if (sscanf(buffer, "%d |%*[^|]|%lf |%lf", &id, &ra, &dec) == 3)
    /* proceed to use `id', `ra', `dec' */
else
    /* invalid line of input */

To understand what the "%*[^|]" means/does read the manual page for scanf(3).


1Use meaningful variable names, with todays text editors it's no extra work as the autocomplete feature will help you a lot, meaningful variable names will make the program easy to understand a few months/weeks later when you get back to it for some reason (maintenance, reuse).

Upvotes: 2

ameyCU
ameyCU

Reputation: 16607

Instead write like this -

  if(sscanf(buffer, "%d | %*[^%|] | %lf | %lf", &id, &ra, &dec)==3){
  /*                      ^ this will read until | is not encountered and then discard it*/
  // do something
 }

Upvotes: 2

Magisch
Magisch

Reputation: 7352

Reading for "%s" (or any variant thereof) will stop reading at a space.

Upvotes: 0

Related Questions