#include <iostream>
#include <string>
#include <sstream> // don't mind this
#include <ctime> //don't mind this either
using namespace std;
int main() {
const string password = "hello"; //password
char word[100]; //if this were string and I put 2 words in my password it would output "invalid password" twice
do {
cin >> word;
cin.getline(word, 100);
if (word == password) { //if word is equal to password, break and move on past the loop
break;
}
cout << "Password invalid" << endl; //password not equal, it will move on to this and repeat until password is true
} while (true);
cout << "Password valid" << endl;
return 0;
}
我已经接触 c++ 编程几个月了,我现在正在观看一门非常好的课程。在其中一个教程中,他制作了上面介绍的密码程序。我已经玩过该程序,并注意到当我输入"示例密码"等 2 个单词时,它会输出两次"无效密码"。我认为这是因为它将空格识别为另一个输入。我做了一些更改,所以现在当我输入 2 个或更多单词时,它只输出一次无效密码。但现在我面临着另一个需要帮助的问题。当我尝试输入正确的密码时,它不起作用。这个谜团的答案是什么?帮助将不胜感激,这可以帮助我和其他人更多地理解这一点,并帮助避免将来出现此问题。
scanf("%[^n]%*c", string );
这里的 [^] 是 scanf 函数的扫描集说明符,这意味着 scanf 函数扫描从 stdin 到换行符的字符。这基本上是一个 c 函数。
cpp 中的并行是 getline(stream, char *( 函数,但几乎所有 c 代码都使用 c++ 工作,因此您可以使用它。