如果条件和字符串
If conditioning and String
我是一个c++新手,非常感谢您的帮助!
我正在尝试为字符串创建一个'If'条件,即,例如:
#include <iostream>
using namespace std;
int main()
{
string message = "HELP";
int password;
cout<<"Please enter password";
cin<<password;
if (password = message);
}
else {
cout<<"Please try again...";
}
cin.ignor()
}
然而,我相信Int不适合字符串,当然在Code::Blocks上它会发布错误,在这种情况下它不起作用。所以基本上,当有人在c++中为int X保存一个变量;X = 3;例如,我们如何处理字母,这样我就可以弹出条件消息框!
再次感谢你的帮助!div = D=分配。==是比较。另外,不要在if语句后面加上分号。
#include <iostream>
using namespace std;
int main()
{
string message = "HELP";
string password;
cout << "Please enter password";
cin >> password;
if (password != message)
{
cout << "Please try again...";
}
return 0;
}
应该会好一点
第一个问题:
int password;
password
的数据类型也应该是std::string
,因为message
是std::string
(其中包含有效密码)。
第一个修改是:
std::string password;
第二个问题是你在if
中使用'='
。使用'=='
(相等运算符),而不是'='
(赋值运算符)
首先,如果您希望密码是任何东西,而不仅仅是一个数字,请使用std::string。要比较两个值,使用== NOT =.
#include <string>
#include <iostream>
int main()
{
std::string s1("First string");
std::string s2("Second string");
if(s1 != s2) {
std::cout << "Strings don't match!" << std::endl;
}
}
在你的代码中,你也没有正确地关闭所有的块,并拼错了cin.ignore()。
你可能想做的是:
#include <iostream>
// using namespace std; don't do this (its just lazy)
// Also its a bad habit to get into.
int main()
{
std::string message = "HELP";
// int password; I assume you want a password to be a string
std::string password;
std::cout << "Please enter password"n; // Added n to make it print nicely.
// cin<<password; The << is wrong should be >>
//
// Bu this reads a single word (separated by spaces).
// If you want the password to hold multiple words then you need
// to read the line.
std::getline(std::cin, password);
// if (password = message); This is assignment. You assign message to password.
// Also the ';' here means that nothing happens
// if it was true
//
// You are then trying to test the result of the
// assignment which luckily does not work.
// Use the '==' to test for equality.
if (password == message)
{
}
else
{
cout << "Please try again...";
}
// cin.ignor() This does nothing.
// What you are trying to do is get the program to wait
// for user input. You should do something like this:
std::cin.ignore(std::numeric_limits<std::streamsize>::max()); // Flush the buffer
std::cout << "Hit enter to continuen";
std::cin.get();
}
在if条件上使用了错误的操作符。您使用了赋值操作符=。你需要使用==,也就是比较。if后面还有一个分号这个分号不属于if语句的括号也不对
相关文章:
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 基于宏中传递的字符串的条件编译
- 将子字符串与字符串数组进行比较的 IF 条件会在C++中产生错误
- 生成具有条件的给定字符串的排列
- C++,使用自己的条件搜索文件中的字符串
- 如何更改此空隙函数,以便在特殊条件下返回一个生成的字符串
- 是否可以将结构与条件语句完全相同的字符串转换为可以读取和操作的语句?
- 虽然第三次循环循环,尽管在我眼中没有满足它的条件,因此打印了一个空字符串
- 如何在没有 c++ 中的数组/算法的情况下对两个条件的字符串进行排序
- 如何在C++中有条件地设置 C 样式字符串?
- 视觉C++错误 C2451 条件字符串是非法的
- 如何在 constexpr 函数内的字符串文字上静态断言条件
- 在 do-while 循环中初始化字符串将在检查条件之前跳转到它
- 如何在 Visual Studio 中基于字符串比较设置条件断点
- 字符串和布尔值(Int 条件为假)C++
- 有条件地确定字符串是否是数组的一部分
- 条件字符串的C++[i]
- if条件下两个字符串比较的优化代码
- 如何使用字符串创建条件