代码将永远不会执行?使用do / while循环时c ++

时间:2019-02-10 20:40:14

标签: c++ xcode xcode10

我在密码功能中放入了一个do / while循环,但是它不起作用。我使用xcode10编码c ++,当我在while语句后使用分号时,它显示错误,指出代码将永远不会执行

string password (string g)
{
    string ch = "hello" ;
    cout << "Enter password";
    getline(cin, g);
    do {
        if (ch.compare(g) != 0) {
            cout << " INCORRECT PASSWORD";
            return (0);
        } else {
            cout << "correct password";
            return (string(g));
        }
    } while (ch.compare(g) == 0);  //this is where it shows the error that the code will never exec
}

我想放这个循环和其他一些东西,这样我就可以使它成为无限循环,直到您输入正确的密码为止。

3 个答案:

答案 0 :(得分:1)

在您的if语句中,两种情况下都将返回,导致函数停止,因此它将永远不会进入while条件进行测试

  string password(string g)
{
    string ch = "hello";
    cout << "Enter password\n";
    do
    {
        getline(cin, g);

        if (ch.compare(g) != 0)
        {
            cout << " INCORRECT PASSWORD\n";
        }
        else {
            cout << "correct password";
            return (string(g));
        }
    } while (ch.compare(g) != 0);  
}

答案 1 :(得分:0)

在“ if”和“ else”中都有Return语句。 您可以看到,无论ch.compare(g)的结果如何,该函数都会返回给它的调用者。

这就是为什么它永远不会执行“ while”的原因。

尝试在代码的不同位置设置Return语句:)

答案 2 :(得分:0)

如果需要EOF,则需要检查是否也得到了输入。

string password() { // you don't need g as parameters in, your overwriting it
    string const ch = "hello"; // make ch const to show it not supposed to change
    cout << "Enter password";
    string g; // defining g here since now you need it
    while (getline(cin, g)) { // check that the read from cin is OK
        if (ch != g) { // simple notation for comparing two strings. There's also == available
            cout << "INCORRECT PASSWORD. Please try again\n"; // no return if you want to try again
        } else {
            cout << "correct password";
            return g; // you could also return ch here since they have the same content
        }
    }
    cout << "Unable to read line. aborting\n"; // not really a lot you can do if there is no input to read.
    return string(); // returning empty string.
}