0

I'm trying to read data from a .txt file with fscanf(), but it won't find values in the file. I want to skip certain values and read some integers as well as floating point numbers, all separated by commas.

I've looked through several threads where people have similar issues, but so far I have not been able to apply any of the recommendations to my case.

The file looks like this:

EURUSD,5,20211224,000000,1.13289,1.1329,1.13273,1.13273,0,0 EURUSD,5,20211224,000500,1.13273,1.13273,1.13233,1.13242,0,0 EURUSD,5,20211224,001000,1.13243,1.13265,1.13233,1.13253,0,0 EURUSD,5,20211224,001500,1.13258,1.13295,1.13253,1.13279,0,0 EURUSD,5,20211224,002000,1.13279,1.13297,1.13255,1.13277,0,0

I open it with

FILE* fivemin = fopen("eurusd.txt", "r");

and then format the input as follows:

while (fscanf(fivemin, "%*s,%*d,%d,%d,%lf,%lf,%lf,%lf,%*d,%*d", &day, &timeat, &ropen, &rhigh, &rlow, &rclose) ==6) {
        printf("%d %d %lf %lf %lf %lf\n", day, timeat, ropen, rhigh, rlow, rclose);
        
    }

The code is executed and the values of day,timeat, ropen, rhigh, rlow and rclose do not change.

Adding or removing \n or \0 to the end of the input format line doesn't help.I've compared fscanf return value to 0 and it doesn't help either, which means that fscanf() can't find anything.

I would appreciate it if someone could tell me what I am doing wrong and how I could scan the values with fscanf() properly.

  • 3
    `%*s` will *not* stop at the comma. It'll consume the whole line, I think. – Steve Summit Feb 20 '22 at 14:09
  • You're going to need to either (a) use the obscure `%[…]` format, or (b) skip `scanf` in favor of something better. (a) might look like `%*[^,]`. For (b), see [What can I use for input conversion instead of scanf?](https://stackoverflow.com/questions/58403537) – Steve Summit Feb 20 '22 at 14:11
  • @SteveSummit it indeed does consume the entire line. – aulven Feb 20 '22 at 14:18
  • @SteveSummit (a) seems to have worked. Thank you! – pieinthesky Feb 20 '22 at 14:23
  • @melonduofromage But if there was a space anywhere in the line, it wouldn't. – Steve Summit Feb 20 '22 at 15:09
  • Since you tagged as C++, use `std::getline` to read into a `std::string`. Create `std::istringstream` using the string. Next, use `std::getline` to read text until a `,` is found. – Thomas Matthews Feb 20 '22 at 19:53

0 Answers0