1

Possible Duplicate:
Why isn’t cin >> string working with Visual C++ 2010?

The first program I wrote refuses to compile in Visual C++, and it looks like it's complaining that the '>>' operator isn't defined for istream.

After looking it over carefully, it seemed to be correct, so I checked with g++ and it compiles fine (and has no warnings with -Wall).

So why does it work with g++ but not Visual C++?

Here is the program:

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

I had thought C++ code written for Visual C++ and C++ code written for g++ would be nearly identical in most circumstances.

How different are they, how often would you say these kinds of issues come up, and do you know of anywhere I can find some of these differences/gotchas?

Community
  • 1
  • 1

1 Answers1

3

Different compilers have different headers that internally include other headers. gcc is probably including <string> inside of <iostream>, while Visual Studio's <iostream> doesn't include <string>. Try putting:

#include <string>

At the top with your other includes. <string> is the header file that defines operator>>(std::istream, std::string) (in other words, <string> is the header that "officially" provides the function you need to do std::cin >> str;).

Cornstalks
  • 37,137
  • 18
  • 79
  • 144