Search code examples
c++fileinputifstreamofstream

How can I read a file that I created in the same program, C++?


I did a program that creates a file of a number in its decimal, hexadecimal and octal form:

int main()
{
    int i;
    cout << "Enter number" << endl;
    cin >> i;
    system("pause");
    CreateFile(i);
    ShowFile();
    return 0;
}

void CreateFile(int i)
{
    ofstream file("file.txt", ios::app);
    file << "--------------------------------\n";
    file << "Number in decimal is:" << i << "\n";
    file << hex << setiosflags(ios::uppercase);
    file << "Number in hex is:: " << i << "\n";
    file << dec << resetiosflags(ios::showbase);
    file << oct << setiosflags(ios::uppercase);
    file << "Number in octal is: " << i << "\n";
    file.close();
}

However I don't know how to read it in the console:

void showFile()
{
    int open;
    ifstream file("file.txt", ios::in);
    while (!file.eof() == false) {
        file >> open;
        cout << "The number is " << open << endl;
    }
}

How can I open it?


Solution

  • You open it exactly they way you did it.

    Your problem is not opening the file, but reading the file. You opened the file just fine. You just can't read it correctly, your problem is something else. You actually have two problems:

    1) You're not checking for the end-of-file condition correctly.

    2) You wrote several lines of text into the file. But the code that reads the file somehow, inexplicably, expects the file to contain only numbers, and not the entire text you wrote into it.

    There's also have a third problem, actually: bad code indentation. Knowing how to indent code correctly improves legibility, and often helps in finding bugs.