首页 > 解决方案 > 在 C++ 中读取文件的问题

问题描述

我在用 C++ 读取文件时遇到问题。将包括相关代码和我的文件示例。先感谢您。

string fileName;
cout << "Enter file name: ";
cin >> fileName;


ifstream inputFile(fileName);
if (inputFile.is_open()) {
    getline(inputFile, line);
    pNum = stoi(line);
    int i = 0;
    
    while (getline(inputFile, line)) {
        double x = stod(line.substr(0, line.find(" ")));
        double y = stod(line.substr(line.find(" ")));
        Point pTemp;
        pTemp.x = x;
        pTemp.y = y;
        p.push_back(pTemp);
        i++;
        cout << "File is open" << endl;
    }
    inputFile.close();
}
else {
    cout << "Problem reading input file" << endl;
}

txt文件(file7.txt)
5.63585 0.0125126
8.08741 1.93304
4.79873 5.85009 8.95962
3.50291 7.46605
8.2284
8.58943 1.74108
5.13535 7.10501

标签: c++algorithmdata-structures

解决方案


我从来没有见过你使用的语法,所以也许试试这个。替换ifstream inputFile(fileName);ifstream inputFile;then 后跟inputFile.open(fileName);.


推荐阅读