以下代码适用于我必须执行的项目,其中我收到一个文本文件,其中包含学生姓名和成绩。然后我必须将其转换为包含他的名字的输出文件,然后是他的平均分数。我收到的文件中有多名学生一行一行。输出应该看起来像
Rzam, Look = 0.00
Bambi, Lambi = 40.47
Coop, Jason = 27.31
但我的只是打印垃圾,如
0x7fffb08e8698 = 0.000x7fffb08e8698 = 0.000x7fffb08e8698 = 0.000x7fffb08e8698 = 0.000x7fffb08e8698 = 0.000x7fffb08e8698 = 0.000x7fffb08e8698 = 0.000x7fffb08e8698 = 0.000x7fffb08e8698 = 0.000x7fffb08e8698 = 0.000x7fffb08e8698 = 0.00
这是我到目前为止所做的:
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
struct Student
{
string fname;
string lname;
double average;
};
int read(ifstream &fin, Student s[]);
void print(ofstream &fout, Student s[], int amount);
int main()
{
const int size = 10;
ifstream fin;
ofstream fout;
string inputFile;
string outputFile;
Student s[size];
cout << "Enter input filename: ";
cin >> inputFile;
cout << "Enter output filename: ";
cin >> outputFile;
cout << endl;
fin.open(inputFile.c_str());
fout.open(outputFile.c_str());
read(fin , s);
print(fout, s, size);
fin.close();
fout.close();
}
int read(ifstream &fin, Student s[])
{
string line;
string firstName;
string lastName;
double score;
double total;
int i=0;
int totalStudents=0;
Student stu;
while(getline(fin, line)){
istringstream sin;
sin.str(line);
while(sin >> firstName >> lastName){
stu.fname = firstName;
stu.lname = lastName;
while(sin >> score){
total *= score;
i++;
}
stu.average = (total/i);
}
s[totalStudents]=stu;
totalStudents++;
}
return totalStudents;
}
void print(ofstream &fout, Student s[], int amount)
{
ostringstream sout;
for(int i = 0; i<amount; i++)
{
sout << left << setw(20) << s[i].lname << ", " << s[i].fname;
fout << sout << setprecision(2) << fixed << "= " << s[i].average;
}
}
答案 0 :(得分:1)
您有一些错误,这些错误已经解决了您的问题:
在print
函数中,您写入ostringstream
,然后尝试将其写入文件流。哪个没问题,但它正在打印ostringstream
缓冲区的地址。因此,进行此更改将使其打印内容:
fout << sout.str() << setprecision(2) << fixed << "= " << s[i].average;
请注意.str()
的使用情况。虽然你根本不需要临时流......
所以做出另一个改变,使它看起来像这样:
fout << sout.str() << setprecision(2) << fixed << "= " << s[i].average << '\n';
您需要将ostringstream sout;
放在循环中,因此每次都会重置它。否则你会得到奇怪的复合输出。
您不会使用您的阅读功能计算的学生人数!所以它总是试图打印10!做这样的事情:
int count = read(fin , s);
print(fout, s, count);
如果没有读取分数,我认为您将除以零。所以你应该加一张支票。
您应确保阅读的学生人数不超过size
。或者更好的是,只需将它们放在std::vector
中并从函数中返回。它更简单,更不容易出错。
每次开始阅读学生时,您需要重置i
,否则后来的学生会被分得过多。每个人都需要有一个独立的计数。
我不知道这些是否是唯一的问题,但肯定会让你开始走上正轨: - )