我试图了解如何从输入文件中读取信息并将该数据写入输出文件。我了解如何从文件中读取并显示其内容,但我不了解如何写入文件或显示其内容。我的程序运行良好,但是当我检查我的输出 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;
}
最佳答案
在 Windows 上,很可能您使用记事本之类的东西打开了输出文件,而您的 C++ 程序没有打开该文件进行输出。如果它不能打开文件,ofstream::open 函数将默默地失败。尝试打开后,您需要检查 outputFile 的状态。就像是
outputFile.open("C:\\Users\\David\\Desktop\\outputfile.txt");
if (!outputFile) {
cerr << "can't open output file" << endl;
}
如果 outputFile 的状态不正常,那么你可以做
outputfile << "foobar";
和
outputfile.flush();
直到奶牛回家,你仍然不会得到任何输出。
关于c++ - 为什么在这个使用 std::fstream 的简单程序中我的输出文件是空的?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7614413/