IF流无法打开文件
ifstream is failing to open file
这是我的代码:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getHighScores(int scores[], string names[]);
int main()
{
ifstream stream;
stream.open("scores.txt");
int scores[32];
string names[32];
stream>>scores[0];
stream>>names[0];
if(stream.fail())
cout<<"It failedn"<<strerror(errno)<<endl;
for(int i=1;i<5;i++)
{
stream>>scores[i];
stream>>names[i];
cout<<i<<endl;
}
cout<<scores[2]<<endl;
stream.close();
return 0;
}
void getHighScores(int scores[], string names[])
{
}
它获取分数[2]的垃圾输出,因为stream.open("scores.txt")无法打开文件。strerror(errno) 给我"没有错误"。
我已经检查了我的文件是否真的被称为"分数.txt.txt"。不是。我也尝试将我的文件移动到"C:\scores.txt"。我试过使用完整地址。我尝试删除它并重新创建它。我也尝试过其他我不记得的事情。![在此输入图像描述][1]我已经尝试了几个小时来解决这个问题,我很绝望。如果有人能帮助我解决这个问题,我将不胜感激。
void gethighscores是我计划稍后使用的功能。
输入文件如下所示:
Ronaldo
10400
Didier
9800
Pele
12300
Kaka
8400
Cristiano
8000
程序的输出如下所示
It failed
No error
1
2
3
4
-858993460
Press any key to continue . . .
我在 Visual Studio Express 2012 for Windows Desktop Microsoft运行它我的操作系统是Windows 7终极64位。
使用 "\" 定义路径时,请使用两个而不是一个C:\ \scores.txt
试试这个:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getHighScores(int scores[], string names[]);
int main()
{
string filename = "scores.txt"; // could come from command line.
ifstream fin(filename.c_str());
if (!fin.is_open())
{
cout << "Could not open file: " << filename << endl;
return 1;
}
int scores[32];
string names[32];
int iter = 0;
while (fin >> names[iter] >> scores[iter])
{
if (++iter >= 32 )
{
break;
}
cout << iter << endl;
}
if (iter >= 2)
{
cout << scores[2] << endl;
}
fin.close();
return 0;
}
void getHighScores(int scores[], string names[])
{
}
让我难倒了一下。 您的C++代码以与输入文本相反的顺序读取分数和名称。 输入文件中的第一行文本是 Ronaldo
,但您的第一个operator>>
是 score[0]
(int
)。 这会导致设置failbit
,因此fail()
返回true
。 它还解释了为什么您最终会得到目标数组元素的垃圾。
颠倒scores.txt
文件或C++解析代码中分数/名称的顺序(但不能两者兼而有之!),您应该很高兴。
它失败的原因是:
int scores[32];
string names[32];
stream>>scores[0];
stream>>names[0];
if(stream.fail())
cout<<"It failedn"<<strerror(errno)<<endl;
默认情况下,scores[0] 和 names[0] 没有任何设置值,它会尝试将它们分配给文件,这会导致文件失败。如果您尝试注释这两行:
stream>>scores[0];
stream>>names[0];
您将看到它不再失败并且工作正常。
- 如何基于平台在制作文件中制作if语句?
- C++:更改 IF 语句中的输出文件
- 为什么我可以将 ifstream 文件置于 if 条件?
- 使用"IF" C++逐行读取文本文件
- 我的C++文件期望用'while'代替 if。最后,它预计会出现'('
- C# 读取完全锁定的文本文件或读取 if 语句外部的输出
- 从.cpp文件中提取与模式匹配的"if"块
- 如何使预处理器 #if 以另一个不同文件中的值为条件
- 为什么我们需要在C++头文件中使用 "#if defined Identifier"?
- IF流无法打开文件
- 使用和if/else语句输出到屏幕或文件
- C++:IF流删除文件的内容
- #if 条件区域是否可以跨越包含文件边界
- IF流CSV从带逗号的文件写回
- C++ IF流文件已打开,但失败
- 如果文件位于 if 语句中,为什么我无法写入文件?
- 可执行文件C++问题:while 循环和 if/else if/else
- if('fstream 对象')如何返回 true 或 false 的值,具体取决于文件是否已打开?
- C++ 在 if/else if 中启动不同的文件
- 简单的c++文件读取使用if流