在 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

解决方法

我从未见过您使用的语法,所以不妨试试这个。将 ifstream inputFile(fileName); 替换为 ifstream inputFile;,然后后跟 inputFile.open(fileName);

,

它有效!我对我一直在使用的 IDE 完全陌生,@Igor 是正确的。我当前的工作目录设置错误。谢谢大家的帮助!