问题描述:
参照《c++程序设计 原理与实践》读写文件代码,程序编译没问题,运行一直抛异常,最后发现是文件路径问题。
解决:
由于读写文件是采用的默认路径,如果文件放置路径不对,一定会运行错误。
正确的是文件应该放在“源码”路径下。如下图:
代码如下:
struct Reading {
int hour;
double temperature;
};
int main()
{
cout << "please enter input file name:";
string iname;
cin >> iname;
ifstream ist{ iname };
if (!ist) error("can't open output file", iname);
string oname;
cout << "please enter name of output file:";
cin >> oname;
ofstream ost{ oname };
if (!ost) error("can't open output file", oname);
vector<Reading> temps;
int hour;
double temperature;
while (ist >> hour >> temperature) {
if (hour < 0 || hour>23) error("hour out of range");
temps.push_back(Reading{ hour,temperature });
}
for (int i = 0; i < temps.size();++i)
ost << '(' << temps[i].hour << ','
<< temps[i].temperature << ")\n";
keep_window_open();
return 0;
}