fstream not Working

Aug 9, 2017 at 4:57pm
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();
}
Aug 9, 2017 at 5:04pm
try to use
std::getline(dataFileOut,item)
instead of dataFileOut >> item
Aug 9, 2017 at 5:06pm
Sorry @Igor, I just tried that. Thanks for the response, but it still doesn't work. Any other options?
Aug 9, 2017 at 5:07pm
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.
Aug 9, 2017 at 5:11pm
@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.