为什么在这个使用 std::fstream 的简单程序中我的输出文件是空的?

DEd*_*s57 3 c++ stl ofstream visual-c++

我试图了解如何从输入文件中读取信息并将该数据写入输出文件。我了解如何从文件中读取并显示其内容,但我不了解如何写入文件或显示其内容。我的程序运行良好,但是当我检查我的输出 txt 文件时,里面什么都没有!我可能做错了什么?输入文件包含 3.1415 2.718 1.414。

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main()
{
float fValue;
fstream inputFile;
ofstream outputFile;

inputFile.open("C:\\Users\\David\\Desktop\\inputFile.txt");
outputFile.open("C:\\Users\\David\\Desktop\\outputfile.txt");

cout << fixed << showpoint;
cout << setprecision(3);
cout << "Items in input-file:\t " << "Items in out-put File: " << endl;

inputFile >> fValue;    // gets the fiest value from the input

while (inputFile) // single loop that reads(from inputfile) and writes(to outputfile)    each number at a time.
{
    cout << fValue << endl; // simply prints the numbers for checking.
    outputFile << fValue << ", "; // writes to the output as it reads numbers from the input.
    inputFile >> fValue; // checks next input value in the file
}



outputFile.close();
inputFile.close();


int pause;
cin >> pause;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*hme 5

在 Windows 上,很可能您使用记事本之类的东西打开了输出文件,而您的 C++ 程序没有打开该文件进行输出。如果它不能打开文件,ofstream::open 函数将默默地失败。尝试打开后,您需要检查 outputFile 的状态。就像是

outputFile.open("C:\\Users\\David\\Desktop\\outputfile.txt");
if (!outputFile) {
  cerr << "can't open output file" << endl;
}
Run Code Online (Sandbox Code Playgroud)

如果 outputFile 的状态不正常,那么你可以做

outputfile << "foobar";
Run Code Online (Sandbox Code Playgroud)

outputfile.flush();
Run Code Online (Sandbox Code Playgroud)

直到奶牛回家,你仍然不会得到任何输出。