首页 > 解决方案 > 如何在执行其余功能之前显示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;
}

标签: c++

解决方案


在 之前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())


推荐阅读