안녕하세요. 그래서 나는 사람의 GPA를 계산하고 나중에 참조 할 수 있도록 그 정보를 저장하는 프로그램을 만들기 시작했습니다. 내 문제는 .txt 파일에 저장된 번호를 읽은 다음 GPA 계산 목적으로 저장하는 방법을 파악할 수 없다는 것입니다. 여기에 미완성 프로그램의 코드가 있으며 도움이 될 것입니다.C++ txt 파일 데이터를 이중 변수로 변환
EDIT : .txt 파일은 다음과 같이 레이아웃되어 있습니다 : 5.0 3.7 5.0 3.7 5.0 4.0 ... 다음은 프로그램 진행 상황이지만, 0의 GPA를받습니다 (부정확). 어휘 캐스팅이 제 문제인지, 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
답장을 보내 주셔서 감사합니다. .txt 파일은 5.0 3.7 5.0 3.7 5.0 4.0 등과 같은 형식으로되어 있습니다. 첫 번째 숫자에 두 번째 숫자를 곱하고 그 값을 저장 한 다음 세 번째 숫자에 네 번째 숫자를 곱하고 그 값을 저장해야합니다. 어떻게하면 좋을지 모르겠다. (어떤 종류의 루프를 생각하고 있지만 어떻게할지는 모르겠다.) – Techmaster37
당신이 원한다고 생각하는 해결책을 제 대답으로 업데이트했습니다. Wikipedia에 따르면 "GPA는 주어진 기간 동안 얻은 학점 점수를 총 학점 수로 나눈 값입니다." 업데이트 된 솔루션 만이 가능합니다. –
정말 고마워요. 코드에 구멍을 뚫어 프로그램을 실행했지만 GPA는 0.86129였습니다. 코드의 모든 내용이 '리더 >> 학점 >> 학년을 제외하고 나에게 의미가있었습니다. 선. 어떻게 작동하고 가능한 대안이 무엇입니까? 도와 주셔서 대단히 감사합니다. – Techmaster37