将TXT文件数据转换为双变量

c++ converting txt file data into double variables

本文关键字:变量 转换 数据 TXT 文件      更新时间:2023-10-16

嗨,所以我开始创建一个程序来计算一个人的GPA,并保存该信息以备将来参考。我的问题是,我不知道如何读取保存在。txt文件中的数字,然后将它们存储起来用于计算GPA。这里是未完成的程序代码,任何帮助将是伟大的

编辑:.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

使用流

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的精度Over float相对较小的速度和内存优势。
  • 函数结束时,当读取器退出时,文件将被关闭的范围。Reader.close()不是必需的,但也不坏要放进去的东西(我只是懒)

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

可以使用它将被读入的字符串(或char)转换为double类型。我猜你想要双倍,因为成绩是4.0,3.7,3.3,3.0等。

或者,您可以直接读入双精度类型。

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

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