无法比较C++中的两个字符串
Can't compare two strings in C++
我在 c++ 中的代码中发现了一些问题。似乎我无法使用 if 运算符比较字符串。这是我的代码:
//correct creds
std::string uname ("admin");
std::string pass ("password");
//input creds
std::string r_uname;
std::string r_pass;
//ui
printf("%s n", "Please enter username");
scanf("%s", r_uname);
printf("%s n", "Please enter password");
scanf("%s", r_pass);
//cred check
if((r_uname == uname) && (r_pass == pass)){
printf("%s", "You are in");
}
else{
printf("%s", "Wrong username/password");
}
包括的库:stdio.h 和字符串
提前谢谢。
您正在使用C++
,默认使用std::cout
并从iostream
std::cin
,除非您有充分的理由不这样做。
在您的情况下,您正在使用scanf()
来读取用户输入。 scanf()
只能读入C
样式的字符串,又名char arrays
。我认为您的代码甚至不会在大多数编译器中编译,因为您传入了std::string
.此外,您正在比较C
样式字符串,这些字符串只是比较数组开头的内存地址。您应该使用 strcmp()
来比较C
字符串。
以下是使用 C++ 比较字符串的方法:
#include <iostream>
#include <string>
int main()
{
//correct creds
std::string uname ("admin");
std::string pass ("password");
//input creds
std::string r_uname;
std::string r_pass;
std::cout << "Enter username: " << std::endl;
cin >> r_uname;
std:: cout << "Enter password: " << std::endl;
cin >> r_pass;
//cred check
if ((r_uname == uname) && (r_pass == pass)){
std::cout << "You're in!" << std::endl;
} else {
std::cout << "Wrong credentials" << std::endl;
}
return 0;
}
要在C++中使用字符串,您应该使用 CIN 或 COUT 而不是 scanf 或 printf。要在C++中使用 cin,您需要包含
这是代码
#include <stdio.h>
#include <string>
*#include <iostream>*
int main(){
//correct creds
std::string uname ("admin");
std::string pass ("password");
//input creds
std::string r_uname;
std::string r_pass;
//ui
printf("%s n", "Please enter username");
//scanf("%s", r_uname);
*std::cin >> r_uname;*
printf("%s n", "Please enter password");
//scanf("%s", r_pass);
*std::cin >> r_pass;*
//cred check
if((r_uname == uname) && (r_pass == pass)){
printf("%s", "You are in");
}
else{
printf("%s", "Wrong username/password");
}
}
相关文章:
- 两个字符串在 c++ 中不相等
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 比较两个字符串后卡在无限循环中
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 我需要帮助在一个类中输入两个字符串并获取其输出
- 两个字符串之间的数学运算
- sscanf() 有两个字符串参数
- 我的字符串数组一次打印出前两个字符串
- 两个 c++ 字符串上的异或
- 函数返回两个字符串的第一个常用字符
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
- 我需要在C++的两个字符串之间找到共同的前缀
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 给定两个字符串 S 和 T.确定与 T 相差最小的 S 子字符串?
- gtest:检查字符串是否等于两个字符串之一
- 交换两个字符串时访问正确的内存时,我遇到了分段错误
- 我可以在系统()中使用两个字符串吗?