如何读取我在同一程序C ++中创建的文件?

时间:2016-05-05 02:53:41

标签: c++ file input ifstream ofstream

我做了一个程序,用十进制,十六进制和八进制形式创建一个数字文件:

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();
}

然而我不知道如何在控制台中阅读它:

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

我该怎么打开它?

1 个答案:

答案 0 :(得分:2)

你完全按照你的方式打开它。

您的问题不是打开文件,而是读取文件。你打开文件就好了。你只是无法正确阅读,你的问题是别的。你实际上有两个问题:

1)你不是checking for the end-of-file condition correctly

2)你在文件中写了几行文字。但是,以某种方式读取文件的代码莫名其妙地希望文件只包含数字,而不是你写入的整个文本。

实际上还有第三个问题:错误的代码缩进。知道如何正确地缩进代码可以提高可读性,并且通常有助于发现错误。

相关问题