Jing Huang
Jing Huang

Reputation: 41

Separate a string and a float number with fscanf in C

I am trying to read from a file which contains one line of data format as GOOG|588.88

I want to copy GOOG into ticker, and copy 588.88 into a float stockprice

I have written the following code to do the job where fr is the file pointer

char tempprice[10]; 
char ticker[10];
fscanf(fr,"%[^|]|%[^\n]\n",ticker,tempprice);
float stockprice = stof(tempprice); //change string to float

The code works OK for ticker, but does not work for stockprice. In other words, GOOG is successfully copied into ticker, whereas 588.88 not. Can anyone help me on that?

Is there any better codes? Thanks.

Upvotes: 0

Views: 509

Answers (2)

paulsm4
paulsm4

Reputation: 121669

1) I agree with user30997: I think scanf "pseudo-regex" is more trouble than it's worth. IMHO...

2) However, I believe this is the solution you're looking for:

#include <stdio.h>

int
main (int argc, char *argv[])
{
    char str[] = "GOOG|5.88";
    char price[80], ticker[80];
    int iret = sscanf (str, "%[^|]%*[|]%s", price, ticker);
    printf ("iret=%d, price=%s, ticker=%s...\n",
        iret, price,  ticker);
    return 0;
}

OUTPUT: iret=2, price=GOOG, ticker=5.88...

Upvotes: 0

Sniggerfardimungus
Sniggerfardimungus

Reputation: 11831

I think I'd just:

char tempprice[10]; 
char ticker[10];
char tmp_chr = fgetc(fr);
char *tmp_ptr = ticker;
while (tmp_chr != '|')
{
  *tmp_ptr++ = tmp_chr;
  tmp_chr = fgetc(fr);
}
*tmp_ptr = '\0'
tmp_chr = fgetc(fr);
tmp_ptr = tempprice;
while (tmp_chr >= '0' && tmp_chr <= '9' || tmp_chr == '.')
{
  *tmp_ptr++ = tmp_chr;
  tmp_chr = fgetc(fr);
}
float stockprice = stof(tempprice); //change string to float

...but that's just me. =] It's weird, I love regexps, but can't stand the scanf mechanisms. Anyone else?

Upvotes: 1

Related Questions