以下代碼適用於我需要做的項目,在該項目中,我收到一個文本文件,該文件的學生姓名和姓氏後跟他的成績。然後我必須將其轉換爲輸出文件,其中包含他的名字,然後是他的平均分數。我收到的文件中有多個學生一行一行地被處理。輸出應該relativly像代碼輸出廢話到輸出文件而不是字符串?
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
這是我到目前爲止有:
#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()' –
已嘗試,但無效 –