【问题标题】:Possible to output console result into text file?可以将控制台结果输出到文本文件中吗?
【发布时间】:2020-08-22 15:16:09
【问题描述】:

我需要将以下控制台数据存储到文本文件中:

enter image description here

但是,将放置输出的文本文件的名称由用户输入。我找不到将所有控制台数据存储在请求的文本文件中的正确方法。由于我使用宽度和特殊空间,我不确定如何去做。

我的代码:

 if(message == "5"){
                cout << "\n[View Data...]" << endl;
                cout << "filtering criteria:" << optionTwo << endl;
                cout << "sorting criteria:" << optionThree << endl;
                cout << "sorting order:" << optionFour << endl;
                cout << "" << endl;
    




            if(optionTwo == "Point2D"){
    
                std::cout.width(5); std::cout << std::right << "X";
                std::cout.width(6); std::cout << std::right << "Y";
                std::cout.width(9); std::cout << std::right << "Dist.";
                std::cout.width(3); std::cout << std::right << "Fr" ;
                std::cout.width(7); std::cout << std::right << "Origin" << endl;
}
}



if(message == "6"){

            cout << "Please enter filename: " ;
            cin >> message6;


        }

【问题讨论】:

    标签: c++ stream


    【解决方案1】:

    当您向cout 发送文本时,您基本上已经在写入一个文件,只是一个名为stdout 的系统标准文件。您只需要打开一个不同的输出文件流并以相同的方式发送输出。

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    ofstream out = ofstream("file.txt", ios::out);
    
    out.width(5);
    out << std:;right << "X";
    

    您不必严格包含ios::out,因为它是ofstream 对象的默认模式。你可以在cppreference阅读更多内容

    【讨论】:

      【解决方案2】:

      您可以为此使用文件流:

      std::cin >> message6;           // read file name from the user
      std::ofstream file {message6};  // open file with that name
      file << "hello world";          // write data to the file 
      

      类似于将数据写入cout,您也可以对file 使用流修饰符。

      【讨论】:

        【解决方案3】:

        我不知道您使用的是什么类型的字符串,但是您可以使用 std::ostream:

         ofstream myfile;
         cout << "Please enter filename: " ;
         cin >> message6;
         myfile.open (message6);
        

        那么你会使用:

        myfile << "Your string.\n";
        

        但是,如果您想将程序的实际标准输出重定向到文件。您可以通过调用参数来做到这一点。并且可以在调用程序时在 IDE 或终端的执行面板中设置

        your_program >> output_file.txt
        

        【讨论】:

        • 如果我还需要打印输出怎么办?
        • 如果您使用程序参数选项,您可以使用:( your_program | tee output_file.txt )。如果您想在代码中同时执行这两项操作,请同时使用 std::cout 和 ofstream。
        猜你喜欢
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 2013-02-22
        • 2020-04-24
        • 1970-01-01
        • 2018-10-24
        • 1970-01-01
        • 2011-07-21
        相关资源
        最近更新 更多