Input Output in the other files

When I put the functions of my program in different files, cin,cout and even declaring fstream objects do not work.What can I do?
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <fstream>

void func(const char* name)
{
    std::ifstream ifs(name);

    std::cout << "file open" << std::endl;
}
Can't I give using namespace std; there?
you'll need your functions defined in a header file (this is needed when parts of a program is split into more than 1 file) and im not sure but somehow you could define your fstream objects in the header as well.
manasij7479 wrote:
Can't I give using namespace std; there?


Don't use this in your header (.h) file. And avoid using it in your source (.cpp) file too.

It is better to use the std prefix. Or to name specific types with your using like this:

1
2
using std::ifstream;
using std::cout;


But never put it in header files in the global scope.
Why is it bad to use "using namespace std;"? Does it create a possibility of things clashing with each other in more complex programs?
Fresh Grass wrote:
Why is it bad to use "using namespace std;"? Does it create a possibility of things clashing with each other in more complex programs?


Yes. In fact it can happen quite easily:

1
2
3
4
5
6
7
8
#include <iostream>
#include <algorithm>
//...
using namespace std;

int main() {
    int count = 0; //uh oh, there is a function in std:: called count
}
Can't something be done , so that whenever I use cout, cin etc.. , they are used with the std:: in the entire program??
Can't something be done , so that whenever I use cout, cin etc.. , they are used with the std:: in the entire program??


Read through the previous posts here. As Galik showed, you can do the following:
1
2
using std::ifstream;
using std::cout;
Isn't that only for only file?
Isn't that only for only file?


What do you mean? Sorry, I didn't understand the question.
I think he means that he has to write "using" sentences for every cpp file. Couldn't you write these sentences in a custom header, so that you could just include the header in every cpp file?

This would save some time if you're writing a lot of programs that use same functions.
Otherwise it could only mess things up, because you'd have to either include a whole bunch of these right away (which loses some of its advantage over "using namespace std;", or add them later on, which could mess up previous programs with the same header.
Topic archived. No new replies allowed.