类不返回正确的变量c ++

时间:2015-11-30 19:45:05

标签: c++

Accounts.h

#include <string>
using namespace std;

class Accounts
{
public:
    Accounts();
    void setUsername(string un){username = un;}
    void setPassword(string pw){username = pw;}
    void setLevel(int lv){username = lv;}


    string getUsername(){return username;}
    string getPassword(){return password;}
    int getLevel(){return level;}
private:
    string username;
    string password;
    int level;
};

此功能正确读取文件(我测试过它)。但每当我尝试从该类中获取变量时,它会给我一些奇怪的符号并且它不起作用。

ifstream fin1("data/accounts/accounts.txt");
    string line;
    for (int i = 0; getline(fin1,line);i++)
    {
        if (i != 0)
        {
            istringstream iss(line);
            string username,password;
            int level;
            iss >> username >> password >> level;
            accounts[i].setUsername(username);
            accounts[i].setPassword(password);
            accounts[i].setLevel(level);
            cout << level << endl;
            cout << accounts[i].getLevel() << endl;
        }
    }

1 个答案:

答案 0 :(得分:4)

void setUsername(string un){username = un;}
void setPassword(string pw){username = pw;}
void setLevel(int lv){username = lv;}

问题在于这行代码。我相信,它应该是void setLevel(int lv){level = lv;}

建议将代码修改为以下内容:

void setUsername(string un){username = un;}
void setPassword(string pw){password = pw;}
void setLevel(int lv){level = lv;}