fstream not Working

Hi. For some reason, the std::cout never prints a value, despite there being items in the .txt file I created. What am I doing wrong here? Thanks in advance!

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

int main()
{
    std::ofstream dataFileIn("DataFile.txt");
    std::ifstream dataFileOut("DataFile.txt");

    std::string currentData;
    std::string item;

    while(dataFileOut >> item)
    {
        std::cout<<item<<"\n";

        currentData += item;
    }

    dataFileIn << currentData << " item";

    dataFileIn.close();
    dataFileOut.close();
}
try to use
std::getline(dataFileOut,item)
instead of dataFileOut >> item
Sorry @Igor, I just tried that. Thanks for the response, but it still doesn't work. Any other options?
First of all, calling the output stream 'dataFileIn' and the input stream 'dataFileOut' is pretty confusing.

The problem is, I think, that both streams point to the same file and std::ofstream by default truncates the file it opens, so by the time std::ifstream gets to it there's nothing in it anymore.
Open a different file for output.
@helios, thanks for the response! Your explanation made perfect sense and helped me find a solution easier than making a separate file.

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
#include<iostream>
#include<fstream>

int main()
{
    std::ifstream dataFileOut("DataFile.txt");

    std::string currentData;
    std::string item;

    while(dataFileOut >> item)
    {
        std::cout<<item<<"\n";

        currentData += item;
    }

    dataFileOut.close();

    std::ofstream dataFileIn("DataFile.txt");

    dataFileIn << currentData << " item";

    dataFileIn.close();
}


This works. Thanks!
Topic archived. No new replies allowed.