Trying to use a string variable with infile.open() is treated as a char in c++

感情迁移 提交于 2019-12-02 05:03:48

There are two overloads for open:

void open( const char *filename, ios_base::openmode mode = ios_base::in );
void open( const std::string &filename, ios_base::openmode mode = ios_base::in );

The second one is only available since C++11. You are apparently either not compiling in C++11 mode or using an out of date compiler. There is another overload that takes const char*, so this should work regardless:

infile.open(fileName.c_str());

you can do following way

ifstream aStream;    
 aStream.open(textFile.c_str());

Replace infile.open(fileName); with infile.open(fileName.c_str());

open() takes a parameter of type const char*. In your case, you are trying to pass a string. The above code should work for your issue.

The answers already given are correct, but the entire answer is scattered between 2 answers and a comment. Here's a more complete answer.

The open() you have used is the overloaded version available since C++11, which takes an std::string parameter for the filename.

void open( const std::string &filename, ios_base::openmode mode = ios_base::in );

However, your compiler seems to have the default behavior of compiling in a pre-C++11 standard, under which open() can only take a const char* parameter (ie, a C string).

void open( const char *filename, ios_base::openmode mode = ios_base::in );

To fix your problem, you can do one of two things:

  • If your compiler supports c++11 compilation, google how to do that. In g++, for example, you'd use g++ -std=c++11 myprogram.cpp (or better yet, the latest C++14 standard with g++ -std=c++14 myprogram.cpp)
  • If you don't want to or can't compile that way, then change your open() to use a C string - infile.open(fileName.c_str());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!