简体   繁体   中英

Reading a text file using C++

I need to read the text file and insert them in to a vector. I Write the vector<KeyPoint> to a text file as follows:

vector<KeyPoint> kp_object;

std::fstream outputFile;
    outputFile.open( "myFile.txt", std::ios::out ) ;
    for( size_t ii = 0; ii < kp_object.size( ); ++ii ){
        outputFile << kp_object[ii].pt.x << " " << kp_object[ii].pt.y <<std::endl;
    }
    outputFile.close( );

When I write the vector to the file it looks like this:

121.812 223.574   
157.073 106.449
119.817 172.674
112.32 102.002
214.021 133.875
147.584 132.68
180.764 107.279

each line separated by a space.

But i couldn't read it and insert the content back to vector. The following code gives me error when reading the content and inserting it vector.

std::ifstream file("myFile.txt");
    std::string str; 
    int i = 0;
    while (std::getline(file, str))
    {
        istringstream iss(str);
        vector<string> tokens;
        copy(istream_iterator<string>(iss),
        istream_iterator<string>(),
        back_inserter<vector<string> >(tokens));

        std::string fist = tokens.front();
        std::string end = tokens.back();

        double dfirst = ::atof(fist.c_str());
        double dend = ::atof(end.c_str());

        kp_object1[i].pt.x = dfirst;
        kp_object1[i].pt.y = dend;

        ++i;
    }

You didn't specify what the error is you are getting. I would suspect that you get a crash when you try to "insert" elements into your std::vector<KeyPoint> , however:

kp_object1[i].pt.x = dfirst;
kp_object1[i].pt.y = dend;

Unless there are, at least, i + 1 elements in kp_object1 this won't work. You probably wanted to use something like

KeyPoint object;
object.pt.x = dfirst;
object.pt.y = dend;
kp_object1.push_back(object);

If your KeyPoint has a suitable constructor, you may be able to use

kp_object1.push_back(KeyPoint(dfirst, dend));

instead.

BTW, I'd decode the individual lines like this:

KeyPoint object;
if (std::istringstream(str) >> object.pt.x >> object.pt.y) {
    kp_object1.push_back(object);
}
else {
    std::cerr << "ERROR: failed to decode line '" << line << '\n';
}

which seems to be a lot more readable, is probably more efficient and even add errors handling.

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