C++ 简单的C++密码程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20985940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:25:22  来源:igfitidea点击:

Simple C++ password program

c++passwordscodeblocks

提问by LoreleiRS

I'm learning to use C++ and I decided to create a password program where the user is asked for the password and it compares the user input to the password and returns a wrong or a right. For some reason, this programs always returns a wrong and I'm not sure why. It must be something to do with comparing the strings but I'm not sure.

我正在学习使用 C++,我决定创建一个密码程序,在该程序中要求用户输入密码,并将用户输入与密码进行比较并返回错误或正确。出于某种原因,这个程序总是返回错误,我不知道为什么。这一定与比较字符串有关,但我不确定。

#include <iostream>
#include <string>
using namespace std;

int main(){
    string pass = "password";
    string input;
    cout << "What is your password: ";
    cin >> input;
    if (input==pass){
        cout << "Correct" << endl;
    }else{
        cout << "Wrong" << endl;
    }
    return 0;
}

I would love some help from programmers who are in any way more well versed in C++ as I've just transferred over to C++ from Python and the transitions a bit rocky.

我希望得到一些更精通 C++ 的程序员的帮助,因为我刚刚从 Python 转移到 C++ 并且转换有点困难。

回答by cLoudsyk

1.you could use compare function, to see:http://www.cplusplus.com/reference/string/string/compare/

1.你可以使用比较功能,查看:http://www.cplusplus.com/reference/string/string/compare/

2.you should debug at line if (input==pass){ to print pass and input and check if they are the same.

2.您应该在 if (input==pass){ 行调试以打印 pass 和 input 并检查它们是否相同。

回答by Steve

I found I needed to:

我发现我需要:

#include <string>

to get the definition of the insertion operator (for cin >> input;) and std::string::operator==() (for if (input==pass)). Once I did that, it worked fine in Visual C++.

获取插入运算符(for cin >> input;)和std::string::operator==()(for if (input==pass))的定义。一旦我这样做了,它在 Visual C++ 中运行良好。

What compiler are you using?

你用的是什么编译器?