compile error: ifstream::open only accepts string values in quotes “” and not string variables

Does open function have some sort of restriction as to what kind of string value is passed in?

ifstream file;
string filename = "output.txt";
file.open(filename);

I tried to pass a string value with a string variable, but when it tries to compile, the result is...

agent.cpp:2:20: error: ofstream: No such file or directory
agent.cpp: In function ‘std::string readingline(std::string)’:
agent.cpp:11: error: aggregate ‘std::ifstream file’ has incomplete type and cannot be     defined
agent.cpp: In function ‘int main()’:
agent.cpp:44: error: aggregate ‘std::ofstream writefile’ has incomplete type and cannot be defined

On the other hand, when I just pass a string value in quotes like "filename.txt" , it compile fine and runs fine.

ifstream file;
file.open("output.txt");

Why is this the case?

Is there a way to solve this problem?

Answers


Sadly, this is how the constructor and open of std::(i|o)fstream are defined by the standard. Use file.open(filename.c_str()).

Some standard libraries provide an extension that allows std::string as a parameter, e.g. Visual Studio.


I got the problem to go away by including fstream and passing filename.c_str() instead of just filename.

The message about an incomplete type is because you are missing a header (probably anyway, you didn't show a full example).

And open takes a c-style string, not the string class.


I think your error messages may be unrelated to the code in question, but open takes a C-style const char* and not a C++ string. You'll need to use filename.c_str() in the call to make it work correctly.


Need Your Help

writing search queries from an application

sql database

I need to search for an entity in my application.

Ensime Vim .ensime file not found

scala vim ensime

I'm trying to get Ensime for Vim working, I compiled the project for ensime using sbt 'update' then 'dist', and compiled the c file, but when i try starting ensime in Vim with :Ensime it prints out...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.