ifstream notworking the way I expected

hi people does anyone know why I won't get any output to the console I'm expecting the firsts econd and third thing I wrote to the file to be printed out

But when I run the program nothing gets printed to the screen any ideas?

thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  #include <fstream>
#include <string>

using namespace std;

int main()
{
    ofstream theFile("haha.txt");
    ifstream File("haha.txt");

    if(theFile.is_open()){
    string one;
    cout << "enter name";
    cout << "\n";
    getline(cin,one);
    theFile << one;
    string first;
    string second;
    string third;
    while(File >> first >> second >> third){
       cout << first << second << third;
    }
    }else{
       cout << "not open";
    }
}
Last edited on
I expect because at the point you're reading from the file, nothing has yet been written to it.

http://www.cplusplus.com/reference/ostream/ostream/flush/
but I thought when i did theFile << one;

I wrote to the file?
<< sends something to the output stream. That stream will get flushed at some time in the future, and that's when the file will be written to. If you want to force it to be flushed, you can use http://www.cplusplus.com/reference/ostream/ostream/flush/
Last edited on
that worked great actually thanks Moschops,I wonder why you have to flush teh file for it to be written I thought it would be written once you do theFile << one;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

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

using namespace std;

int main()
{
    ofstream theFile("haha.txt");
    ifstream File("haha.txt");

    if(theFile.is_open()){
    string one;
    cout << "enter name" << endl;
    cout << "\n";
    getline(cin,one);
    theFile << one;
    string first;
    string second;
    theFile.flush();
    while(File >> first >> second){
       cout << first << second;
    }
    }else{
       cout << "not open";
    }
}
Last edited on
Works fine when I run that code.

I suggest breaking at line 22 with a debugger and examining the haha.txt file at that point.
yup works fine,I just entered too much information in,it works perfect =)
I wonder why you have to flush teh file for it to be written I thought it would be written once you do theFile << one;


If you read the C++ documentation, you'll find that << doesn't write files. It puts something into the stream. That's what it does. The << operator doesn't write anything to a file. It's not what it does. You simply misunderstood what the << operator does. I expect that wherever you learned it from didn't fully explain it, probably to keep things simple.
Last edited on
thanks I got to do some more study on that
hey Moschops or anybody else could you tell me where to find more info about the << operator?

thanks
Topic archived. No new replies allowed.