如何使变量等于C++中的字母

How to make a variable be equal to a letter in C++?

本文关键字:C++ 何使 变量      更新时间:2023-10-16

我尝试用C++制作一个简单的程序,因为我是初学者。该程序应该告诉您"赃物值",因此如果您在控制台中编写除"Nicu"(我的一个朋友的名字)之外的任何内容,该程序将显示"赃物级别超过 9000"。如果你写"Nicu",虽然它会说"对不起,在数据库中找不到赃物"。我的问题是,当我写"Nicu"时,如何让程序给我这个答案?以下是我对该程序的看法:

#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
    char b,a;
    a='Nicu';
    cout<<"Insert your name: ";
    cin>>b;
    if (b==a){
    cout<<"Sorry ! Couldn't find swag in database... "<<endl;
}
    else if (b!=a){
    cout<<"Swag level over 9000 "<<endl;
}
system ("PAUSE");
return 0;
}

这是它给我的错误:[错误]Id 返回了 1 个退出状态,它突出显示了代码的a='Nicu'部分。即使我在此代码中使用了char,我仍然不知道它的作用,但至少我确定int不能与字母一起使用。

char用于

存储单个字符

可以使用std::string来存储字符串。

重写

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
  string a = "Nicu";
  string b;
  cout<<"Insert your name: ";
  cin>>b;
  if (b==a){
    cout<<"Sorry ! Couldn't find swag in database... "<<endl;
  }
  else if (b!=a){
    cout<<"Swag level over 9000 "<<endl;
  }
  system ("PAUSE");
  return 0;
}
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
string b, a;
a = "Nicu";
cout<<"Insert your name: ";
cin>>b;
if (b==a){
cout<<"Sorry ! Couldn't find swag in database... "<<endl;
}
else if (b!=a){
cout<<"Swag level over 9000 "<<endl;
}
system ("PAUSE");
return 0;
}
为什么

不使用字符串而不是字符?对于比较字符串,您应该使用"strcomp"

    #include <stdio.h>
    #include <string.h>
int main()
{
    string other;
    string that;
    if(strcmp(other, "hi")) // comparing the characters in this string with the text possibility "hi."
    {
    // do whatever you want if they are equal.
    }
    //Or.
    if(strcmp(other, that)) // comparing both strings rather than a string with a possibly extracted text to compare it with alongside another string comparing both strings at once.
    {
    // do whatever you want if they are equal.
    }
}