适用于g ++但不适用于MSVC ++

时间:2013-01-27 03:57:02

标签: c++ visual-c++ g++

  

可能重复:
  Why isn’t cin >> string working with Visual C++ 2010?

我在Visual C ++中编写refuses to compile的第一个程序,看起来它抱怨'>>'运算符未定义为istream。

仔细查看之后,似乎是正确的,所以我用g ++检查它编译得很好(并且没有-Wall警告)。

那为什么它适用于g ++但不适用于Visual C ++?

以下是该计划:

#include <iostream>
#include <list>

int main() {
    std::list<std::string> list;
    std::string str = "";
    std::cin >> str;
    while (str.compare("q") != 0) {
        list.push_back(str);
        std::cin >> str;
    }

    std::cout << "You entered: \n";

    for (std::list<std::string>::iterator i = list.begin(); i != list.end(); i++) {
        std::cout << *i << std::endl;
    }
    return 0;
}

我曾经认为为Visual C ++编写的C ++代码和为g ++编写的C ++代码在大多数情况下都几乎相同。

它们有多不同,你多久会说出这类问题,你知道我能找到一些差异/陷阱吗?

1 个答案:

答案 0 :(得分:3)

不同的编译器具有不同的标头,内部包含其他标头。 gcc可能包含<string>内的<iostream>,而Visual Studio的<iostream>不包含<string>。试试看:

#include <string>

在顶部与您的其他包括。 <string>是定义operator>>(std::istream, std::string)的标头文件(换句话说,<string>是“正式”提供您需要执行的功能std::cin >> str;)的标头。