错误:不匹配'operator>>'在'std :: cin

时间:2014-08-20 18:33:36

标签: c++ compiler-errors

我回来了另一个可能是noob的问题。 XP

所以我现在有这个。

#include <iostream>

using namespace std;

int main()
{
    string input;

    int man;

    cout<<"Choose your Character- 1.Sven or 2.Macy: ";
    cin>>input;
    cin.ignore();

    if ( input == "Sven" ){
        cout<<"Welcome to CRPG, my good Sir!";
        return 0;
        cin>>"Sven starts his journey at the Forest of Despair. At the beginning of the path, a fork in the road sits in his way. Which path shall you take? L or R?";
    }

    else if ( input == "Macy" ){
        cout<<"Girls cant fight, go back: ";
    }
}

是的,我已经看过并阅读过有关同一问题的其他帖子,但似乎没有一个适用于我。那么我能解决这个问题的方法是什么?

3 个答案:

答案 0 :(得分:2)

主要问题是这行代码:

cin>>"Sven starts his journey at the Forest of Despair. <blah blah blah>";

当然,cin不提供operator>>,因此代码无法使用您描述的错误消息进行编译。但是,假设它确实提供了这样一个运营商。那么你的代码意味着什么呢?您正在尝试将读入字符串文字(即const char[N]类型,其中N是字符串的长度),这是常量且无法修改的。

由于你想要某些东西到输出(而不是从输入中读取内容),你应该使用cout <<代替。

另请注意,您有return 0将阻止语句执行,因为遇到该语句后main的执行将停止。


更新:根据评论,请注意,尽管您在程序中使用了#include <string>,但仍未std::string。虽然您可以使用此功能,但您不应该依赖此行为,而应明确包含您使用的内容。正如Slava和MooingDuck建议的那样,如果不这样做,可能会导致类似于您报告的错误。

答案 1 :(得分:2)

您必须包含标题<string>

#include <string>

此标头包含operator >>

类型对象的std::string声明

同样在本声明中

   cin>>"Sven starts his journey at the Forest of Despair. At the beginning of the path, a fork in the road sits in his way. Which path shall you take? L or R?";
你有一个错字。应该有cout <<而不是cin >>

答案 2 :(得分:1)

在这种情况下你正确使用了cin:

cin>>input;
cin.ignore();

为什么不在这里也这样做?

string direction 
cout << "Sven starts his journey at the Forest of Despair. At the beginning of the path, a fork in the road sits in his way. Which path shall you take? L or R?";
cin >> direction

//do whatever you want to do with direction

编辑:

为什么你有

return 0;

这不会让程序在此行之后执行任何操作,因为您将返回此处。