gpt4 book ai didi

c++ - 为什么它只能读取第一行?

转载 作者:行者123 更新时间:2023-11-28 04:30:05 25 4
gpt4 key购买 nike

我是 C++ 的初学者。这是学校作业的一部分。这是登录部分。

我需要从一个包含许多用户 PIN 的外部文件中读取 PIN。

我需要将用户刚刚输入的 pin 与存储在文件中的 pin 进行比较。如果 pin 匹配,则用户成功登录。如果没有,则用户还有 2 次尝试再次输入 PIN。

我现在面临的问题是除了第一行我无法读取其他行的数据。

当我输入其他正确的 PIN 码时,程序总是显示错误的 PIN 码。只有当我输入第一行时,它才会显示正确的 PIN。

请帮我找出问题所在。谢谢。

069906

777329

143003

069021

void olduser ()
{
int userpin,a;
cout << "*************************************************************" <<
endl << endl;
input.open("userdata.txt");
cout << "Please enter your PIN." << endl;
cin>>userpin;

if(input.is_open())
{
while(input >> pin)
{

if(userpin == pin) //compare the pin typed in with the pin in file
{
cout << "You have entered the correct PIN." << endl <<endl;
cout << "You have successfully login." << endl <<endl;
cout << "Redirecting......" << endl;
system("pause");
break;
}
else if (userpin != pin)
{
for(a=1;a<=2;a++)
{
cout << "You have entered the wrong PIN." << endl;
cout << "Please try again." << endl;
cin >> userpin;

if(userpin == pin)
{
cout << "You have entered the correct PIN." << endl <<endl;
cout << "You have successfully login." << endl <<endl;
cout << "Redirecting......" << endl;
system("pause");
break;
}

}
system("cls");
cout << "The PIN you have entered has no match." <<endl <<endl;
cout << "Please try again later. Thank you." << endl << endl;
cout << "Exiting IVM......" << endl;
system("pause");
break;
}
}
}
else
{
cout << "Unable to open file." << endl;

}

}

int attempts = 0;
while (attempts < 3)
{
bool logged = false;
if (input.is_open())
{
while (input >> pin)
{
if (userpin == pin)
{
//if the PIN is found in the external file

cout << "You have successfully login." << endl << endl;
cout << "Redirecting to main menu......" << endl;
system("pause");
logged = true;
mainmenu();
}
}
}
else
{
//If the external file cannot be opened
cout << "Unable to open file." << endl;
break;
}
if(logged) break;
{
//if the PIN is not found in the external file
cout <<"The PIN is not matched. Please try again." << endl;
cin>>userpin;
}
attempts++;
}
if(attempts == 3)
{
//the login is unsuccessful after using up 2 attempts
cout <<"Your PIN is not matched. Please try again next time." <<endl
<< endl;
}

最佳答案

答案很简单:所有可能的代码路径都会导致在其第一次迭代中中断 while 循环,因此它只会从 input 中读取第一行。

此外,由于上述原因,在您的 else if (userpin != pin) 中,您的 for 循环将始终检查相同的 pin.

示例解决方案:

int loginAttempts = 0;
while (loginAttempts < 3)
{
//Prepare file to reading
bool logged = false;
if (input.is_open())
{
while (input >> pin)
{
if (userpin == pin)
{
//Handle successful login attempt
logged = true;
break;
}
}
}
else
{
//Handle file openning failure
}
if(logged) break;
//Handle unsuccessful login attempt
loginAttempts++;
}
if(loginAttempts == 3)
{
//Handle unsuccessful login
}

关于c++ - 为什么它只能读取第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53191135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com