【问题标题】:Output a value to console after do...while statement is satisfied?在 do...while 语句满足后输出一个值到控制台?
【发布时间】:2019-05-02 02:44:09
【问题描述】:

我对 C++ 非常陌生,无法真正弄清楚这一点。我尝试了几件事,但我觉得我只是缺少一些简单的东西。

我有这个控制台应用程序,用户可以在其中输入预定义的密码。如果密码不正确,它会提示他们重新输入密码。如果密码正确,则只是结束程序,但我希望它说“授予访问权限!”然后结束。

我遇到的一个附带问题是,当输入多个单词作为密码时,每个单词都会打印“拒绝访问”。

string password;

cout << "Please enter the password!" << endl;
cin >> password;

if (password == "test") {
    cout << "Access granted!";
} else {
    do {
        cout << "Access denied! Try again." << endl;
        cin >> password;
    } while (password != "test");
}

return 0;

【问题讨论】:

  • 您需要将if / else 逻辑移动到循环内。
  • 查看这个问题,了解为什么cin 只读取一个单词:stackoverflow.com/questions/9469264/…(还要注意std::string 比原始的char 数组更好更安全)
  • @πάνταῥεῖ 你要创建一个答案吗?
  • "cout &lt;&lt; "Access granted!"; 移动到循环之后将是最简单的更改。
  • @CelticTree 这是一个非常简单的项目,目标简单,没有明显的限制。所以解决方案也可能很简单。这不太可能具有挑战性。此外,更简单的通常更清洁。原则上,要求更清洁的解决方案通常与要求更具挑战性的解决方案相反。

标签: c++ console-application


【解决方案1】:

您需要在循环退出后输出您的"Access granted" 消息,并且您还需要在每次失败尝试丢弃任何仍在等待读取的单词后清除标准输入输入:

#include <limits>

string password;

cout << "Please enter the password!" << endl;
cin >> password;

if (password == "test") {
    cout << "Access granted!";
} else {
    do {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Access denied! Try again." << endl;
        cin >> password;
    } while (password != "test");
    cout << "Access granted!";
}

return 0;

Live Demo

这样写会更好:

#include <limits>

string password;

cout << "Please enter the password!" << endl;
do {
    cin >> password;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    if (password == "test") break;
    cout << "Access denied! Try again." << endl;
}
while (true);

cout << "Access granted!";
return 0;

Live Demo

但是,请注意 operator&gt;&gt; 一次只能读取 1 个单词,因此类似 "test I GOT IN!" 的内容也将被接受。您应该使用std::getline() 来一次读取整行,而不是一次读取一个单词:

#include <limits>

string password;

cout << "Please enter the password!" << endl;
do {
    getline(cin, password);
    if (password == "test") break;
    cout << "Access denied! Try again." << endl;
}
while (true);

cout << "Access granted!";
return 0;

Live Demo

【讨论】:

  • 谢谢!这同时回答了我的两个问题。解决方案确实很简单,但我不确定我是否会弄清楚。一个附带错误是,如果“test”是字符串中的第一个单词,即使后面跟着其他东西,它仍然会接受它。但我会自己解决这个问题,谢谢你的帮助!
  • 那是因为operator&gt;&gt; 一次只读取一个单词。改为使用std::getline() 一次读取一行。
猜你喜欢
  • 2020-05-07
  • 2015-06-19
  • 2016-01-10
  • 1970-01-01
  • 1970-01-01
  • 2016-04-18
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多