所以我写了一段代码来从txt文件中获取数据,然后对它进行一些计算。但是,我试图在其余功能执行之前将txt文件的原始内容打印到屏幕上,并且遇到了一些问题。它要么不打印到屏幕,要么使我的输出文件为空或仅显示一行。任何有关做什么的帮助将不胜感激!
#include fstream
#include iostream
#include iomanip
#include string
using namespace std;
int main()
{
// defines the input/out streams for the data file
ifstream dataIn;
ofstream dataOut;
// Contains amount item purchased
int a, b, t, noOfDishes;
int res, res1;
string inputfile;
cout << "Please enter the name of the file you want to open:" << endl;
getline(cin, inputfile);
// Opening the input file
dataIn.open(inputfile);
cout << infile1.rdbuf();
// checking whether the file name is valid or not
if (dataIn.fail())
{
cout << "** File Not Found **";
return 1;
}
else
{
// creating and Opening the output file
dataOut.open("output.txt");
while (dataIn >> a >> b >> t)
{
res = 0;
noOfDishes = 0;
dataOut << a << "\t" << b << "\t" << t << "\t";
res1 = a;
res = a;
while (true)
{
if (res <= t)
{
noOfDishes++;
res1 = (res1 + b);
res += res1;
}
else
break;
}
dataOut << noOfDishes << endl;
}
// Closing the input file
;
dataIn.close();
cout << " Data Written to output.txt " << endl;
// Closing the output file.
dataOut.close();
}
return 0;
}
答案 0 :(得分:0)
在dataOut.open()
之前,添加以下行以显示文件的内容:
char ch = dataIn.get();
while(ch != EOF){
cout << ch; //Output character
ch = dataIn.get();
}
dataIn.clear(); //Remove the dirty bit EOF
这一步一步读取文件的字符,并将其输出到控制台,直到到达文件末尾
编辑:
正如@Some Programmer Dude指出的那样,如果您的编译器将char
视为无符号类型,则代替:
while(ch != EOF)
使用:
while(!dataIn.eof())