如果条件和字符串

If conditioning and String

本文关键字:字符串 条件 如果      更新时间:2023-10-16

我是一个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,因为messagestd::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语句的括号也不对