我如何让这个程序读取这个人键入的字符串,看看字符串是否相等

How do I get the this program to read what the person type as a string and see if the strings are equal?

本文关键字:字符串 是否 程序 读取      更新时间:2023-10-16

我需要帮助...如何让此程序读取此人键入的字符串并查看字符串是否相等?

        #include <iostream>
        using namespace std;
        int main()
        {
            char name;
            cout << "Type my name is:";
            cin >> name;
            if
               name ==char('Mike') //this is where i think the problem is...
                cout << "congrats";
            else
            cout << "Try again";
        }
#include <iostream>
int main()
{
    std::string name;
    std::cout << "Type my name is:";
    std::cin >> name;
    if (name == "Mike") // Compare directly to the string "Mike"...
        std::cout << "congrats";
    else
        std::cout << "Try again";
}

我认为使用std::而不是using namespace std总是更好的习惯。

你试过在 c++ 中使用 std::string 吗?

    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
        string name;
        cout << "Type my name is:";
        cin >> name;
        if (name == "Mike"))
            cout << "congrats";
        else
            cout << "Try again";
    }

你的问题是char是一个字符变量,而不是一个字符数组。如果要创建"c-string"(字符集合),请使用 char name[20] 。要创建字符串对象,请使用 string name 。不要忘记#include <string>.下面是字符串的简短教程:http://www.cplusplus.com/doc/tutorial/ntcs/

如果要使用 c 字符串,则必须使用 strcmp(name,"Mike") 来比较两个字符串。如果两个字符串不同,则返回 true,因此要小心。

#include <iostream>
using namespace std;
int main()
{
    char name[20];
    cout << "Type my name is:";
    cin >> name;
    if (!strcmp(name,"Mike")) //C string equality tester
        cout << "congrats";
    else
        cout << "Try again";
}

字符串更易于使用,因为您可以只使用相等运算符 ==

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string name;
    cout << "Type my name is:";
    cin >> name;
    if (name == "Mike") //Tests for equality using strings
        cout << "congrats";
    else
        cout << "Try again";
}

另外,请注意引号。单引号('a')用于字符,双引号("Mike")用于字符数组(单词,句子等)。

char是一个

字符,请将所有char替换为std::string,并将#include <string>添加到代码的开头。 std::string将保存任意长度的字符串。

if后跟大括号:if(...) 。在您的情况下if(name == char('Mike'))或根据上面的建议if(name == std::string('Mike')).

在 C 和 C++ 中,两个引号'"是不同的。'用于单个字符,"用于字符串。所以它需要if(name == std::string("Mike")).

你也可以写if(name == "Mike").

此外,您还应该制作括号以提高可读性并避免错误。if(...)后,您通常会使用 {} 来封装在满足 if(...) 中的条件时要执行的指令。您的情况很特殊,因为括号可能会被省略为单个说明。

if(...)
{
    ...
}
else
{
    ...
}
int main()
{
  string name;
  string myname("Mike");
  cout << "Type my name is:";
  cin >> name;
  if(name ==myname) //this is where i think the problem is...
  { 
    cout << "congrats";
  }
  else
    cout << "Try again";
}

这应该可以做到。但我相信你不想只硬编码"迈克"。一个很好的改进是从文件中获取名称,然后进行比较。还要记住,字符串 == 运算符区分大小写,因此 "Mike" != "mike"