c ++将txt文件数据转换为双变量

时间:2013-04-29 01:38:22

标签: c++ file casting double lexical

嗨所以我开始创建一个程序来计算一个人的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

3 个答案:

答案 0 :(得分:0)

看看这个函数:http://www.cplusplus.com/reference/cstdlib/atof/

您可以使用它将正在读入的字符串(或字符串)转换为double。我假设你想要双倍,因为成绩是4.0,3.7,3.3,3.0等。

答案 1 :(得分: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或 正则表达式。
  • 返回double而不是float,通常需要double的精度 超过浮动的速度和内存优势相对较小。
  • 当阅读器退出时,文件将在功能结束时关闭 范围。 reader.close()不是必需的,但不会是坏事 放入的东西(我只是懒惰。)

答案 2 :(得分:0)

或者,您可以直接阅读双重内容。

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

另外,在你的WriteGrades函数中,为什么要在行之前而不是在结尾处写出新行(使用endl而不是'\ n')?

相关问题