2013-04-29 3 views
-1

안녕하세요. 그래서 나는 사람의 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 

답변

0

사용하여 스트림 :

double calculateGPA() { 
    double credit_sum = 0.0, grade_sum = 0.0; 
    double credit, grade; 
    ifstream reader("grades.txt"); 

    while (!reader.eof()) { /* while the file still has numbers to be read */ 
     reader >> credit >> grade; 

     if (reader.fail()) { 
      /* something unexpected happened (read error/formatting error) */ 
      break; 
     } 

     credit_sum += credit; 
     grade_sum += grade; 
    } 

    if(credit_sum == 0.0) { 
     /* avoid divide by zero */ 
     return 0.0; 
    } 

    /* divide the total grade by the total credits */ 
    return grade_sum/credit_sum; 
} 

주 :

  • 이 .txt 인 단지 숫자가 파일 (크레딧을 가정, 학년, 학점, ...) 공백으로 구분 (공백 또는 줄 바꿈) : 좀 더 복잡한 서식을 지정하려면 scanf 또는 정규 표현식을 사용하십시오.
  • float 대신 double을 반환하면 대개 double의 정밀도 보다 float의 상대적으로 작은 속도와 메모리 이점이 필요합니다.
  • 기능의 끝에서 파일이 닫히고 리더는 범위가 이 될 때 닫힙니다. reader.close() 직접 두 번에 읽을 수 필요는 없지만 넣어 나쁜 일이되지 않을 것 (난 그냥 게으른입니다.)
+0

답장을 보내 주셔서 감사합니다. .txt 파일은 5.0 3.7 5.0 3.7 5.0 4.0 등과 같은 형식으로되어 있습니다. 첫 번째 숫자에 두 번째 숫자를 곱하고 그 값을 저장 한 다음 세 번째 숫자에 네 번째 숫자를 곱하고 그 값을 저장해야합니다. 어떻게하면 좋을지 모르겠다. (어떤 종류의 루프를 생각하고 있지만 어떻게할지는 모르겠다.) – Techmaster37

+0

당신이 원한다고 생각하는 해결책을 제 대답으로 업데이트했습니다. Wikipedia에 따르면 "GPA는 주어진 기간 동안 얻은 학점 점수를 총 학점 수로 나눈 값입니다." 업데이트 된 솔루션 만이 가능합니다. –

+0

정말 고마워요. 코드에 구멍을 뚫어 프로그램을 실행했지만 GPA는 0.86129였습니다. 코드의 모든 내용이 '리더 >> 학점 >> 학년을 제외하고 나에게 의미가있었습니다. 선. 어떻게 작동하고 가능한 대안이 무엇입니까? 도와 주셔서 대단히 감사합니다. – Techmaster37

0

봐 : http://www.cplusplus.com/reference/cstdlib/atof/

당신은 문자열 (또는 문자)를 변환하는 데 사용할 수는 이중으로의 읽을. 나는 등, 등급 4.0, 3.7, 3.3, 3.0이기 때문에 당신이 두 번한다고 가정

+0

atof (및 atoi)는 오류를 확인할 수있는 확실한 방법을 제공하지 않습니다. 이런 이유로 C 방식으로 수행하려면 scanf를 사용하는 것이 좋습니다. –

0

을 또는. 또한

calculateGPA() 
{ 
    double credit; 
    ... 
    reader >> credit; 
    ... 
} 

, 당신의 WriteGrades 기능에, 당신은 왜 당신의 라인 전에 대신의 말에 새로운 라인 (대신 '\ n을'의 사용 ENDL)를 작성하는거야?

+0

답장을 보내 주셔서 감사합니다. 왜 그런 식으로했는지 모르겠지만 의견을 보내 주시면 감사하겠습니다. – Techmaster37