使用 C++ 读取文本文件

Reading a text file using C++

本文关键字:文件 取文本 读取 C++ 使用      更新时间:2023-10-16

我需要读取文本文件并将它们插入到向量中。我将vector<KeyPoint>写入文本文件,如下所示:

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( );

当我将向量写入文件时,它看起来像这样:

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

每行用空格分隔。

但我无法阅读它并将内容插入回矢量。下面的代码在读取内容并插入矢量时给我错误。

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;
    }

您没有指定您遇到的错误。我怀疑当您尝试将元素"插入"std::vector<KeyPoint>时会出现崩溃,但是:

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

除非kp_object1至少有i + 1元素,否则这是行不通的。您可能想使用类似的东西

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

如果您的KeyPoint具有合适的构造函数,则可以使用

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

相反。

顺便说一句,我会像这样解码各个行:

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';
}

这似乎更具可读性,可能更有效,甚至增加了错误处理。