为什么我总是收到这个文件错误

Why do I keep getting this file error?

本文关键字:文件 错误 为什么      更新时间:2023-10-16

我试图从一个文件中读取信息,然后它将转换读取的信息并将其输出到另一个文件。然后,我需要删除原始文件,并重命名包含更新信息的第一个第二个文件。我试图通过调用原始文件,转换信息并将信息保存到新文件中,然后使用C++中的delete函数和rename函数来实现这一点。知道为什么我打开文件时出错吗?

data.txt包含

  • XCIX
  • 4999
  • XI
  • IX
  • 55
  • 95

temp.txt为空

两者都保存在C:\Users\Owner\Documents\Visual Studio 2013\Projects\Roman Numbers\Debug 中

int main() 
{
fstream dataFile;   
fstream outfile;    
string line;
string output;
outfile.open("temp.txt", ios::out);
dataFile.open("data.txt", ios::in);
if (!dataFile)
{   
    cout << "File Errorn";
}
else
{
    cout << "Opened correctly!n" << endl;
    while (dataFile)
    {
        if (dataFile.eof()) break;
        getline(dataFile, line);
        if (line[1] == '1' || line[1] == '2' || line[1] == '3' || line[1] == '4' || line[1] == '5' || line[1] == '6' || line[1] == '7' || line[1] == '8' || line[1] == '9' || line[1] == '0')
        {
            outfile << numbertonumberal(line) << "n";
        }
        else
        {
            outfile << romantonumberal(line) << "n";
        }
    }
    dataFile.close();
    remove("data.txt");
    rename("temp.txt", "data.txt");
    cout << "All values have been converted are are in the original filen";
    outfile.close();
}

return 0;
}

我的输出是一行,上面写着"文件错误"。

首先:检查文件。它存在吗?你在代码上有一些错误:

if (!dataFile) // incorrect. datafile is instance of class but not ponter
if (datafile.is_open()) // correct. use a method from fstream class
while (dataFile) // incorrect. its true while object "datafile" exists (see above)
while (!datafile.eof()) // correct. And you don`t need "if (dataFile.eof()) break;"

所以,你的代码应该是这样的:

if(datafile.is_open()) {
    while(!datafile.eof()) {
        getline(datafile, line);
        ... // use isdigit() function for compare with digits (<cctype> header)
    }
} else {
    cerr << "Cannot open file" << endl;
}