【发布时间】:2016-11-01 03:13:23
【问题描述】:
以下代码用于我必须执行的一个项目,我收到一个文本文件,其中包含学生的名字和姓氏,后跟他的成绩。然后我必须将其转换为一个输出文件,其中包含他的名字和他的平均分数。我收到的文件中有多个学生逐行排列。输出应该看起来像
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.00 P>
这是我目前所拥有的:
#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;
}
}
【问题讨论】:
-
看起来您将内存地址称为垃圾...尝试使用 c_str() 处理 fname 和 lname 字符串...例如
s[i].fname.c_str() -
试过但无济于事
标签: c++ string file filestream stringstream