我收到变量“count”未初始化的错误。但它应该在读取并验证文件中的数据后进行初始化。C++

1 c++ variables fstream

我正在开发登录/注册系统。到目前为止,我收到的错误是变量“count”在未初始化的情况下被使用。

bool count;
string userId, password, id, pass;
system("cls");
cout << "\t\t\n Please enter the username and password\n\n";
cout << "Username:";
cin >> userId;
cout << "Password:";
cin >> password;
//reads info from the file
ifstream readL("record.txt");
while (readL >> id >> pass) {
    if (id == userId && pass == password) {
        count = true;
    }
    else {
        count = false;
    }
}
readL.close();

if (count == true) {
    cout << userId << " your LOGIN is successfull.\n\n";
    main();
}
else {
    cout << "\nLOGING error\n\nPlease check your username and password\n\n\n";
    main();
}
Run Code Online (Sandbox Code Playgroud)

我有代码的第二部分,相同的系统在这里工作。`

case 1: {
        bool count;
        string suserId, sId, spass;
        cout << "\n\nEnter the username that you remember:";
        cin >> suserId;
        //reads the file
        ifstream f2("records.txt");
        while (f2 >> sId >> spass) {
            if (sId == suserId) {
                count = true;
            }
            else {
                count = false;
            }
        }
        f2.close();
        if (count == true) {
            cout << "\n\n\tYour account is found!\n\nYour password is " << spass << endl << endl;
            main();
        }
        else {
            cout << "\n\n\tSorry your account is not found." << endl << endl;
            main();
        }
        break;
}
Run Code Online (Sandbox Code Playgroud)

`

唯一的区别是,在第一种情况下,它在 while if 语句中读取两个变量,在第二种情况下,仅读取用户名。但即使我在第一种情况下只读取用户名,错误仍然出现。

Sam*_*hik 5

您的 C++ 编译器足够聪明,可以判断出如果文件无法打开或为空,则循环while永远不会执行一次,并且count在循环后检查其值之前一直保持未初始化状态。这就是你的 C++ 编译器告诉你的。

仅仅因为输入文件存在或不为空,并且其内容有效(因为其中的垃圾也会导致初始尝试读取它失败)并不重要。从逻辑上讲,当它的值被使用时,它可能count未被初始化,因此编译器会进行诊断。

PS,while出于不同的原因,循环的逻辑也存在致命缺陷。但这与您询问的编译器诊断无关。