简体   繁体   中英

Read a text file in C++

I am working in Ubuntu on OpenCV. I am trying to read a text file which contains numbers, but I keep getting garbage values and the same value repeats every time the function loops. Here is that part of the code:

FILE* fid = fopen("/trial","r");
while (fgetc(fid) != EOF)
{
    fscanf(fid, "%f", &trainsample);
    cout << trainsample << endl;
    cvSetReal2D(traindata, i, j, trainsample);
    j = j + 1;
    if (j == 6)
        i = i + 1;
}

Why don't you use C++ ifstream for this task?

#include <iostream>
#include <fstream>

int main(){
    std::ifstream fileStream("/trail");
    double trainsample;
    if(!fileStream.good()){
        std::cerr << "Could not open file." << std::endl;
        return 1;
    }
    while(fileStream >> trainsample){           
        std::cout << trainsample << std::endl;
    }
    if(fileStream.fail())
        std::cerr << "Input file stream error bit is set, possible read error on file." << std::endl;               
}

If you prefer C file handling try

#include <cstdio>

int main(){
    FILE *fid = fopen("/trail","r");
    double trainsample;
    if(fid){
        while(!feof(fid)){
            fscanf(fid,"%lf",&trainsample); // Please notice "lf" when using double. Using "f" will result garbage.
            printf("%lf\n",trainsample);
        }
    }
}

See also cstdio and ifstream .

fgetc() reads a character from a file. It is equivalent to getc. You can use !feof(fid) as your condition instead. The garbage values are because you are not at the correct position while reading the float values from the file and as a result, other characters/special characters are influencing the values being read in by C.

Is there any particular reason you're using C-style I/O routines instead of C++ stream operators?

#include <iostream>
#include <stdexcept>
#include <fstream>
...
std::ifstream fid("/train");
if (!fid.good())
    // could not open file, panic here
else
{
  float trainsample;
  while (fid >> trainsample)
  {
    std::cout << trainsample << std::endl;
    ...
  }
  if (fid.eof())
    std::cout << "Hit end of file" << std::endl;
  else if (fid.fail())
    std::cout << "Read error on file" << std::endl;
}

ASSUMPTION:

  • The /trail file contains only one float value per line

Having said the above, you don't need the while loop with fgetc() , instead you need the following

while (fscanf(fid,"%f",&trainsample) == 1) {
    cout<<trainsample<<endl;
    /* you can put all you logic here */

}

我的猜测是fopen失败,因此fscanf失败(不读取任何内容),而实际上您获得的垃圾值是trainsample变量的未初始化内容,当然,该内容永远不会改变。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM