为什么我总是收到这个文件错误
Why do I keep getting this file error?
我试图从一个文件中读取信息,然后它将转换读取的信息并将其输出到另一个文件。然后,我需要删除原始文件,并重命名包含更新信息的第一个第二个文件。我试图通过调用原始文件,转换信息并将信息保存到新文件中,然后使用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;
}
相关文章:
- C++系统找不到指定的文件错误
- C++语法头文件错误
- C++生成文件错误"implicit entry/start for main executable"
- C++/生成文件错误:未定义对"main"的引用
- VS2019:资源文件错误:中性(默认)(未知子语言:0x8)
- C++程序不制作文件(错误)
- 安卓工作室 |CPP 文件错误错误: 位图库中对"AndroidBitmap_unlockPixels"的未定义引用
- "what does ":*** [可执行文件] 错误 1 " mean ?"
- 如何修复使用VScode调试器gcc调试时的"找不到文件"错误
- 在课堂上创建了一个朋友,给出"无输入文件"错误
- Qt .exe文件错误
- c++ 添加具有写入文件错误的文本变量
- 无法转换 .CATPart 文件.错误:输入文件路径似乎包含不支持的字符
- 写入文本文件错误,QT
- C++写入文件错误
- Windows Subsystem for Linux (WSL) 下的间歇性随机"找不到文件"错误
- 犰狳读取MAT文件错误
- 无法求解FullPathForFilename:COCOS2DX中可能缺少文件错误
- C Wininet FTP列出了许多文件错误
- 生成文件错误 - 找不到文件 - *.cpp