Differences in reading file using ifstream in g++ and msvc

c++, filestream, ifstream, std, stream

Solution

Chances are that you forgot to `#include <string>`. Without it, Microsoft's version of `<iostream>` (and such) include enough of a declaration of `std::string` for some things to work, but other parts are missing, so you get strange, seemingly inexplicable failures.

One of the things that's missing is most of the operator overloads for `std::string`, which is exactly what you seem to be missing.

As an aside, `while (myfile.good()) ...` is pretty much a guaranteed bug -- you probably want:

while (myfile>>myString)
    std::cout << myString << " \n";

Alternatively, you could do the job with a standard algorithm:

#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <iostream>

int main() { 
    std::ifstream myfile("input.txt");

    std::copy(std::istream_iterator<std::string>(myfile),
              std::istream_iterator<std::string>(),
              std::ostream_iterator<std::string>(std::cout, " \n"));
    return 0;
}

Problem

When using ifstream class to read words from an input file, I have used the following expression: ``` #include <iostream> #include <fstream> int main(int argc, char *argv[]) { std::ifstream inputStream(myFile.txt); std::string myString; myFile.open() while(myFile.good()) { myFile >> myString; printf("%s \n", myString); } return 0; } ``` The contents of myFile.txt are: " This is a simple program. " The compiles and executes as expected using g++ compiler. However, the same code when compiled using msvc 2008, returns error at the extraction operator (>>) requiring me to replace the std::string with either an initialized character array or any of the supported native types. This threw me off as I was expecting the usage of the standard library to be same across implementations. I understand the compile error and know the way to fix it via using c_str(). But, it would help me a great deal, if someone could clarify why the usage for the standard library is different across platforms. To me it is not starndard anymore !! EDIT: Code updated to be complete. Content of myFile.txt updated.

Original source