嗨所以我开始创建一个程序来计算一个人的 GPA 并保存该信息以供将来参考。我的问题是我不知道如何读取保存在 .txt 文件中的数字,然后将它们存储起来用于 GPA 计算。这是未完成程序的代码,任何帮助都会很棒
编辑: .txt 文件的布局如下: 5.0 3.7 5.0 3.7 5.0 4.0 ... 以下是我在程序中的进度,但是当我运行它时,我收到的 GPA 为 0(不正确)。不确定词汇转换是我的问题,getline() 方法还是其他问题。有什么帮助(calculateGPA() 方法是问题所在)?
#include <iostream>
#include <fstream>
#include <string>
#include <boost/lexical_cast.hpp>
using namespace std;
string newCC, newCG;
double curGPA;
char command;
bool running = 1;
void calculateGPA();
void writeGrades();
void mainMenu();
void addClass();
int main()
{
while(running) {
mainMenu();
}
return 0;
}
void calculateGPA()
{
double credit_sum = 0.0, grade_sum = 0.0;
double credit, grade;
ifstream gReader("grades.txt");
for( int i = 0; ! gReader.eof() ; i++ )
{
string number;
getline( gReader , number ) ;
double dblNumber;
try
{
dblNumber = boost::lexical_cast<double>(number);
}
catch (boost::bad_lexical_cast const&)
{
dblNumber = 0;
}
credit_sum = credit_sum + dblNumber;
}
ifstream cReader("credits.txt");
for( int i = 0; ! cReader.eof() ; i++ )
{
string number;
getline( cReader , number ) ;
double dblNumber;
try
{
dblNumber = boost::lexical_cast<double>(number);
}
catch (boost::bad_lexical_cast const&)
{
dblNumber = 0;
}
credit_sum = credit_sum + dblNumber;
}
if(credit_sum == 0.0) {
curGPA = 0.0;
}
curGPA = (grade_sum / credit_sum);
cReader.close() ;
gReader.close() ;
}//End calculateGPA
void writeGrades()
{
string cToWrite = newCC + "\n";
string gToWrite = newCG + "\n";
ofstream cWriter("credits.txt", ios::app);
cWriter << cToWrite;
ofstream gWriter("grades.txt", ios::app);
gWriter << gToWrite;
cWriter.close();
gWriter.close();
}//End writeGrades
void addClass()
{
cout << "New class' credits?"; cin >> newCC;
cout << endl << "New class' grade? (GP)"; cin >> newCG;
writeGrades();
cout << "Add another class? (y/n)" << endl; cin >> command;
if(command == 'y')
addClass();
else mainMenu();
}//End addClass
void mainMenu()
{
string command;
cout << "What would you like to do?" << endl;
cout << "(V)iew GPA" << endl;
cout << "(A)dd grades" << endl;
cout << "(E)xit" << endl;
cin >> command;
if(command == "v")
{
calculateGPA();
cout << "Your current GPA is " << curGPA << endl;
}
else if(command == "a")
{
addClass();
}
else running = 0;
}//End mainMenu