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

时间:2015-03-08 07:27:47

标签: c++ char

我尝试用C ++编写一个简单的程序,因为我是初学者。该程序应该告诉你“赃物价值”,所以如果你在控制台中写任何东西,除了“Nicu”,这是我的一个朋友的名字,程序会说“Swag level over 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不能用于字母。

3 个答案:

答案 0 :(得分:1)

#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;
}

答案 1 :(得分:1)

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;
}

答案 2 :(得分:0)

为什么你不使用字符串而不是char? 比较你应该使用的字符串&#34; strcomp&#34;

    #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.
    }
}