所以我的計劃是採取建立一個程序,它看起來類似於這樣的輸入:我需要一個替代方法來串流字符串。 C++
Boole, George 98 105 -1 -1 -1
Pascal, Blaise 63 48 92 92 92
Babbage, Charles 100 97 100 98 -1
Kepler, Johannes 75 102 100 -1 -1
Clown, Bozo 0 6 6 57 62
Fini, End -99 -99 -99 -99 -99
和輸出這樣的:我有麻煩
Student Submission Grade
Boole, George 2 105
Pascal, Blaise 3 92
Babbage, Charles 1 100
Kepler, Johannes 2 102
Clown, Bozo 5 62
,因爲我現在的代碼可以成功編譯它,但我的其他輸入文件之一遵循不同的格式。我當前的代碼:
int main()
{
ifstream infile;
ofstream outfile;
infile.open("./ProgGrades1.txt");
outfile.open("./GradeReporttest.txt");
string lastName, firstName;
int score1, score2, score3, score4, score5;
int max, location;
while(GetInput(infile, lastName, firstName, score1, score2, score3, score4,
score5))
{
if (score1 == -99)
break;
AnalyzeGrade(infile, lastName, firstName, score1, score2, score3,
score4, score5, max, location);
WriteOutput(infile, outfile, lastName, firstName, max, location);
cout << lastName << " " << firstName << " " << location << " " << max <<
endl;
}
infile.close();
outfile.close();
return 0;
}
int GetInput(ifstream& infile, string& lastName, string& firstName, int& score1,
int& score2, int& score3, int& score4, int& score5)
{
infile >> lastName >> firstName >> score1 >> score2 >> score3 >>
score4 >> score5;
return infile;
}
int AnalyzeGrade(ifstream& infile, string& lastName, string& firstName,
int& score1, int& score2, int& score3, int& score4, int& score5,
int& max, int& location)
{
int score[5];
max = 0;
score[0] = score1;
score[1] = score2;
score[2] = score3;
score[3] = score4;
score[4] = score5;
for (int i = 0; i < 5; i++)
{
if (score[i] > max)
{
max = score[i];
}
}
if (max == score[0])
{
location = 1;
}
else if (max == score[1])
{
location = 2;
}
else if (max == score[2])
{
location = 3;
}
else if (max == score[3])
{
location = 4;
}
else if (max == score[4])
{
location = 5;
}
else
{
}
fill_n(score, 6, 0);
return infile;
}
void WriteOutput(ifstream& infile, ofstream& outfile, string& lastName,
string& firstName, int& max, int& location)
{
string studentID = lastName + " " + firstName;
outfile << "\n" << setw(19) << studentID << setw(14) << location << " " <<
max;
}
我的其他輸入文件看起來像:
Stroustrup, Bjarne 8 8 -1 -1 -1
Lovelace, Ada 1 60 14 43 -1
von Neumann, Jon 77 48 65 -1 -1
Wirth, Niklaus 51 59 -1 -1 -1
Wozniak, Steve 81 -1 -1 -1 -1
Babbage, Charles 31 92 -1 -1 -1
Hopper, Grace 76 -1 -1 -1 -1
Bird, Tweety -99 -99 -99 -99 -99
Sylvester 77 39 -1 -1 -1
所以這裏的問題是,在兩個字符串我INFILE流,但在第3行有兩個部分姓氏,最後一行有一個名字。我需要一種替代方法來獲取名稱。
btw我目前在C++課程介紹,所以我的知識是有限的,但我沒有任何疑慮研究。正如你所看到的,我正在使用更多的入門級代碼。我試圖使用數組,但我的結論是,我仍然不明白如何成功傳遞它們。
我的代碼基本上達到了同樣的結論。使用變量lastName和firstName,我可以獲取整個名稱並將其輸出爲一個字符串。第3行有逗號,但姓氏有兩個部分,所以會混亂。 – hanipman
'std :: getline(infile,',')'將提取所有內容到第一個逗號並放棄逗號。也許你可以使用它。 –
這對於第三行是有效的,但不是最後一行,因爲沒有逗號需要停下來。 – hanipman