-1

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?

πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175
Ivano
  • 5
  • 3
  • `while (!archivo.eof() == false) ` so you want to read the file only if EOF is reached? Also note that `archivo` isn't declared in the posted code. – MikeCAT May 05 '16 at 03:05
  • All of that doesn't make sense. You're writing some text into your output file and then want to read a single number from it? Such requires more sophisticated parsing. – πάντα ῥεῖ May 05 '16 at 03:06
  • Please check [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) also. – πάντα ῥεῖ May 05 '16 at 03:08
  • `open` is a pretty weird variable name for something to be read from the file BTW. – πάντα ῥεῖ May 05 '16 at 03:15

1 Answers1

2

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.

Community
  • 1
  • 1
Sam Varshavchik
  • 84,126
  • 5
  • 57
  • 106