2017-03-31 92 views
-1

有人可以检查我的代码是否坏?当我执行它时,我的命令提示符崩溃。我的C++程序不断崩溃ist我的代码不好?

我将问题范围缩小到本节:

string result = ""; 
    result = pwpasst (username, password, "admin", "123"); 
    result = pwpasst (username, password, "root", "456"); 
    result = pwpasst (username, password, "peter", "789"); 

如果我注释掉2出的3个功能似乎工作。 + 我不知道我的代码是坏的还是我的命令提示符有问题。

的其余代码:

#include <iostream> 

using namespace std; 

    string pwpasst (string username, string password, string un, string pw){ 
     if (username == un && password == pw) 
     { 
      return "You are logged in!"; 
     } 
    }; 

int main() 
{ 
    string username; 
    string password; 

    cout << "Enter your username: "; 
    cin >> username; 

    cout << "Enter your password: "; 
    cin >> password; 


    string result = ""; 
    result = pwpasst (username, password, "admin", "123"); 
    result = pwpasst (username, password, "root", "456"); 
    result = pwpasst (username, password, "peter", "789"); 

    if (result != "You are logged in!"){ 
     cout << "Wrong password or username!"; 
    } else { cout << result;} 
} 
+5

不是所有通过'pwpasst'的路径都返回一个值。 –

+4

如果'(username == un && password == pw)'评估为false,则调用undefined-行为。 – George

+2

作为一种预防措施,你应该编译你的代码,总是带有诸如'-Wall'这样的选项,在这种情况下会给你一个警告,例如'warning:控制到达非空函数结束' –

回答

1

pwpasst()可能返回字符串“你是......”

但else子句缺失,不返回任何,一个逻辑错误。 你的函数应该总是返回它承诺的字符串。

string pwpasst (string username, string password, string un, string pw) 
{ 
    if (username == un && password == pw) 
    { 
     return "You are logged in!"; 
    } 
    else 
    { 
     // perhaps - but not a good choice. 
     std::cerr << "unknown user name or password" << std::endl; 
     return ""; // return null string 
    } 
}; 

不是一个好的选择,因为以前每次都会输出1或2条错误消息。


在这个代码片段中,三个赋值将始终执行。

string result = ""; 
result = pwpasst (username, password, "admin", "123"); 
result = pwpasst (username, password, "root", "456"); 
result = pwpasst (username, password, "peter", "789"); 

你想打出来,当你得到一个结果,类似于以下,(但这是不是一个好的选择其一):

string result = ""; 
do { 
    result = pwpasst (username, password, "admin", "123"); 
      if(result.size()) break; 
    result = pwpasst (username, password, "root", "456"); 
      if(result.size()) break; 
    result = pwpasst (username, password, "peter", "789"); 
      if(result.size()) break; 
}while(0); 

可能需要将错误消息在这代码片段,不在函数中。

需要进行一些逻辑更改。也许函数应该返回一个bool(表示有效的名称/ pw或不),并且字符串'result'可以通过引用传递给函数来填充。

+0

我的典型选项:-ggdb -std = C++ 14 -Wall -Wextra -Wshadow -Wnon-virtual-dtor -pedantic -Wcast-align -Wcast-qual -Wconversion -Wpointer-arith - Wunused -Woverloaded-virtual –

+0

非常感谢您的帮助 – Yannic

1

您缺少return语句,如果if (username == un && password == pw)是假的,和你的函数定义,string值需要在其结尾的函数返回。这会调用未定义的行为,这会导致程序以运行时错误终止。

+0

注意:你的逻辑错误程序。由于你的问题不属于他们,我没有把它们包括在这里。如果您还有其他问题,可以在评论栏中提问。 –

+0

非常感谢您的帮助 – Yannic