如何使用 class 构造函数从文件中获取值? C++

How do I use a class constructor to get a value from a file? C++

对不起,如果这很明显,我是 classes 的新手。

我希望代码从 class 构造函数(getter)读取文件的第一个值,现在构造函数 returns 是一个随机数而不是文件的第一个数字,所以显然由于某种原因它没有读取文件。谢谢大家的帮助,代码在下面link。

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

class bankAccount
{
public:
    int getAcctNum();
    bankAccount(string n);
    bankAccount();

private:
    ifstream sourceFile;
    char tempWord;
    int accountNumber;
    double initialBalance;
    double interestRate;
    double serviceCharge;
    double depositAmt;
    double withdrawAmt;
    double totalDeposits;
    double totalWithdraws;
    double tempAmt;

};
int main()
{
    string fileName;
    cout << "Enter the name of the data file: ";
    cin >> fileName;
    cout << endl;
    bankAccount object(fileName);
    cout << "Account number: " << object.getAcctNum() << endl;
    return 0;
}

bankAccount::bankAccount(string n)
{
    ifstream sourceFile(n.c_str());
}
bankAccount::getAcctNum()
{
    sourceFile >> tempWord;
    sourceFile >> accountNumber;
    return accountNumber;
}

它应该读取的文件中的值是: #123456

您的问题与 scope 有关。对于快速 TL;DR 如何修复它,只需一直滚动到底部即可。

考虑 scope 的一种简单方法是思考:我的变量在哪里定义。在 main 之外定义的变量被称为具有全局 scope,因为它是一个全局变量。这意味着无论您在哪里引用它(在定义之后),它都将被定义(不需要初始化,但是)。如果一个变量是在一个函数中定义的,那么它的范围就限于该函数。所以它只会在那个函数中定义,不会在其他函数中定义。如果您在 for 循环或 if 语句中定义一个变量,或者您使用 { } 打开一个新范围的任何地方,该变量是 scope-limited,即它是仅在该范围内定义,并且在读取右大括号后将停止定义。这是一个例子:

#include <iostream>
// rest of includes and usings and function prototypes, etc

const string AUTHOR_NAME = "ME"; // this is now defined everywhere in the program.

int main() {
    bool program_busy = true; // this is only defined in main()
}

bool return_program_busy() {
    cout << AUTHOR_NAME << endl; // this works as AUTHOR_NAME is defined
    return program_busy; // this won't work, as program_busy is not defined in this scope.
}

void better_example(bool program_busy) {
     int version = 0.1;
     for(int i = 0; i < 10; i++) {
         do_something(version, i); // this works as both are defined.
     }
     // i is no longer defined as we exited it's scope!!
     if(program_busy) { // this opens a new scope.
         int version = 0.2;
         do_something(version, 0); // wait, is version 0.1 or 0.2???
     }
}

正如您在最后一行中无疑看到的那样,定义了两个版本(具有不同的范围)。那么它用的是哪一个呢?范围较小的那个,或者local多的那个。 version 0.2 只在 if(program_busy) 范围内定义,所以它比整个函数范围小,所以使用它。您现在可以发现自己代码中的错误吗?

ifstream sourceFile 有两个作用域:一个是全局-class,即它是为整个 class 定义的,另一个是你拥有的构造函数的局部作用域。

ifstream sourceFile(n.c_str()); 将创建一个具有有限范围的新变量并对其进行初始化,使 sourceFile 具有更全局的范围未初始化。修复它的方法只是 而不是 重新定义 sourceFile 变量。

TL;DR:将 ifstream sourceFile(n.c_str()); 更改为 sourceFile.open(n.c_str());