c++ - 如何在执行其余功能之前显示txt文件的内容
问题描述
所以我写了一段代码来从一个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;
}
解决方案
在 之前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())
推荐阅读
- python - 在 python 中从 windows-1252 转换为 utf-8
- apache - 如何根据条件重写 URL?
- java - 如何在 Android Studio VideoView 中自动重播视频
- c++ - 如何在C++中导入和导出同名的不同函数
- excel - 如果单独的工作表包含匹配的单元格,则 Excel 条件格式单元格
- mediawiki - 如何嵌入
模板中的标签仅在原始页面上设置类别 - reactjs - 基于用户位置的 React Native API 调用
- r - 如何从 R 运行带有特定模块的 perl 脚本?
- c - 如何从函数内部调用 ucontext.h getcontext
- r - 如何在ggplot2中将函数添加到具有不同映射的散点图中