您可以在“使用C ++编程原理实践” 书第348页中检查此代码。没有书写错误,我认为使用相同变量名称“ 名称”时会出错。 或代码顺序顺序。 当我运行此代码并要求我输入一个文件名作为输入,输入另一个文件名作为输出时,该程序关闭,没有任何影响或错误。
#include "std_lib_facilities.h"
using namespace std;
// struct Reading
struct Reading {
int hour;
double temperature;
Reading(int h, double t) : hour(h), temperature(t) {}
};
int main()
{
cout << "Please enter input file name: ";
string name;
cin >> name;
ifstream ist(name.c_str()); // ist reads from the file named "name"
if (!ist)
error("can't open input file ", name);
cout << "Please enter name of output file: ";
cin >> name;
ofstream ost(name.c_str());
if (!ost)
error("can't open output file ", name);
vector<Reading> temps;
int hour;
double temperture;
while (ist >> hour >> temperture) {
if (hour < 0 || 23 < hour)
error("hour out of range", "While reading");
temps.push_back(Reading(hour, temperture));
}
for (int i = 0; i < temps.size(); ++i)
ost << '(' << temps[i].hour << ',' << temps[i].temperature << ")\n";
return 0;
}
答案 0 :(得分:0)
我更改了陈述顺序,输入了:
vector<Reading> temps;
int hour;
double temperture;
while (ist >> hour >> temperture) {
if (hour < 0 || 23 < hour)
error("hour out of range", "While reading");
temps.push_back(Reading(hour, temperture));
}
这行代码之后...
if (!ist)
error("can't open input file ", name);
////完整版
#include "pch.h"
#include "std_lib_facilities.h"
#include <iostream>
#include <string>
using namespace std;
// struct Reading
struct Reading {
int hour;
double temperature;
Reading(int h, double t) : hour(h), temperature(t) {}
};
int main()
{
cout << "Please enter input file name: ";
string name;
cin >> name;
ifstream ist(name.c_str()); // ist reads from the file named "name"
if (!ist) error("can't open input file ", name);
//why the book typed it here
vector<Reading>temps;
int hour;
double temperture;
while (ist >> hour >> temperture) {
if (hour < 0 || 23 < hour) error("hour out of range", "While reading");
temps.push_back(Reading(hour, temperture));
}
//end
cout << "Please enter name of output file: ";
cin >> name;
ofstream ost(name.c_str());
if (!ost) error("can't open output file ", name);
for (int i = 0; i < temps.size(); ++i)
ost << '(' << temps[i].hour << ','
<< temps[i].temperature << ")\n";
// output result to console window... modification by me!
for (int i = 0; i < temps.size(); ++i)
cout << '(' << temps[i].hour << ','
<< temps[i].temperature << ")\n";
keep_window_open("quit");
return 0;
}
////结束
..您必须像这样格式化输入文件:
1 60.6
2 45.5
3 70.5
,输出文件将是:
(1,60.6)
(2,45.5)
.....
还有一个。
谢谢你们对我的帮助!