繁体   English   中英

为什么我不断收到此文件错误?

[英]Why do I keep getting this file error?

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

data.txt包含

  • XCIX
  • 4999
  • XI
  • 55
  • 95

temp.txt为空

两者都保存在C:\\ Users \\ Owner \\ Documents \\ Visual Studio 2013 \\ Projects \\ Roman Numerals \\ 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 Error\n";

}
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 file\n";
    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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM