2

Ok so I haven't used C++ since highschool (used to work in borland C++)

Now I want to solve a problem in C++, yet I don't understand why fstream doesn't work

For some reason ios::in doesn't work.

#include <fstream>
fstream f("Cities.txt,ios::in);

How do I use Fstream properly?

Thanks in advance!

Note : I'm using Visual Studio 2008

1
  • First: Terminate the Filename with another '"'. Commented Nov 10, 2012 at 11:35

5 Answers 5

5

change from

fstream f("Cities.txt,ios::in);

to

std::fstream f("Cities.txt" , std::ios::in);
^^^                       ^   ^^^
namespace          you miss"  namespace

done!

Sign up to request clarification or add additional context in comments.

Comments

3

What you have learned in your highschool probably was way before C++ was standardized in '97. As per the standard, all C++ library functions are part of the std namespace. In order to use fstream which is part of the standard namespace, you have to qualify it with std:: so, that makes your syntax as

#include <fstream>
std::fstream f("Cities.txt",std::ios::in); 

Comments

1

As an alternative to std::fstream, consider std::ifstream (and std::ofstream):

#include <fstream>

…

std::ifstream f("Cities.txt");
std::ofstream o("output.txt");
std::string s;
while( f >> s )
  o << s; 

Personally, I find this more convenient than specifying the open mode.

Comments

1

You have to first create an object of ifstream class and then open the file. Do it this way.

#include <fstream>

std :: ifstream f ("Cities.txt",ios::in) ;

Then check whether it is open and start working with it.

You are also missing the " after file name.

Comments

0

You can also write

#include <fstream>
using namespace std;
fstream f("Cities.txt",ios::in);

The using directive allows you to not write std:: before everything. Beware, it might be bad practice, but in small programs it should not be an issue.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.