问题描述:

My code looks like this

ifstream myfile;

string fileName;

cin >> filename;

myfile.open(fileName);

I'm getting a rather lengthy error message and can't figure out how to pipe it to a file(I tried a couple things and think I might not have permissions, since I'm on my school's remote terminal), so I took a screenshot.

Sorry if that's taboo, but it was the quickest thing I could think of. The line it is referencing(main.cpp 22) is the line

myfile.open(fileName);

Again, compiles and runs perfectly in Visual Studio 2013, but not in this linux shell. Honestly, if anyone could help me understand the error message that would be a start.

Thanks in advance for any help

网友答案:

You need to use the compiler flag -std=c++11. The following program compiles and builds fine on my machine using:

g++ -Wall -std=c++11    test-484.cc   -o test-484
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
   ifstream myfile;
   string fileName;
   cin >> fileName;
   myfile.open(fileName);
   return 0;
}

BTW, in your posted code, you have

   string filename;
              ^^ lower case n not upper case N
网友答案:

If you are not using C++11, you can also do the following:

#include <iostream>
#include <fstream>
#include <string>

int main () {
std::ifstream myfile;
std::string fileName;
std::cin >> fileName;
myfile.open(fileName.c_str());
}

But accessing the C string directly this way is not a good thing, if possible, follow R Sahu's suggestion to use C++11.

相关阅读:
Top