错误:操作数类型不兼容(" int"和" const char *")c ++

时间:2015-02-12 19:43:21

标签: c++

这是我的代码,错误显示在标题中。在编译器中:

1>c:\users\ägaren\documents\visual studio 2010\projects\yt tutorial hd\yt tutorial hd\main.cpp(26): error C2446: '==' : no conversion from 'const char *' to 'int'

1>c:\users\ägaren\documents\visual studio 2010\projects\yt tutorial   hd\yt tutorial hd\main.cpp(26): error C2040: '==' : 'int' differs in levels of       indirection from 'const char [4]'
#include <iostream>
#include <windows.h>
#include <string> 
using namespace std;


int main()
{
   int gold=600, level=1, exp, damage=10, health=100, mana=100, manaLevel=1;          // Main Vars      
   string name;
   cout << "Hello, what is your name?: ";
   cin >> name; 
   cout << "Welcome " << name << " to the field of war,\nYou will stumble upon many other brave warriors.\nTake care and good luck.\n";
   Sleep(500);

   cout << "You're first task is to eliminate the Orc leader.\n";
   int orc=15, troll=25, mage=50; // Enemy Vars
   int healthpotion=25, manaPotion=25; // Potions vars
   int ifAttack; // if the user chooses to attack or not.
   Sleep(500);
   cout << "Tossan: " << name << " I hereby order you to attack the orc, he is up north.\nThis message will delete in 2.5 seconds.";
   Sleep(2500);
   system("cls"); // 1st screen clear.
   cout << "After heading north you stumble upon the Orc, will you attack him? [y/n]\n";
   cin >> ifAttack;
   if (ifAttack == "yes")

}

if(ifAttack ==“是”) 是什么给了我错误,==有下划线但我无法找到如何解决它。 C ++

1 个答案:

答案 0 :(得分:1)

声明ifAttack不是int,而是像:

string ifAttack;

然后您就可以像以前一样阅读它:cin >> ifAttack;

但是,因为您只关心用户是否输入了“&#39;对于第一个字符,将if语句更改为:

if(ifAttack.front() == 'y' || ifAttack.front() == 'Y')

修改

过滤用户输入可能是一项艰巨的任务。但是,如果您决定要采用它,则可以比较整个 string而不仅仅是第一个字符。就这样&#34;黄色大象&#34;并不意味着&#34;是&#34;:

if(_stricmp(ifAttack.c_str(), "yes") || _stricmp(ifAttack.c_str(), "y"))

_stricmp是仅限Microsoft的功能:https://msdn.microsoft.com/en-us/library/k59z8dwe.aspx strcasecmp是Linux等价物:http://pubs.opengroup.org/onlinepubs/009695399/functions/strcasecmp.html

我建议您保存过滤输入,直到项目结束。这可能很乏味。例如,上面的字符串比较不匹配&#34;是!&#34;。