【问题标题】:How do you copy everything from the console's output to a text file?如何将控制台输出中的所有内容复制到文本文件中?
【发布时间】:2019-09-26 03:14:07
【问题描述】:

我已经尝试过 Sink 和 SaveHistory 来执行此操作,但都没有成功。我还尝试了诸如来自答案之一的这个问题的代码之类的东西。 How to output to the console in C++/Windows。我在 Visual Studio 2019 的空解决方案中制作了所有内容。

没有任何错误,但是当我这样做时:

    ofstream myfile;
    myfile.open("Addresses.txt");
    myfile << printf << endl;
    myfile.close();
    return 0;

它打印出随机数。

//Code I tried
#include <iostream>

using namespace std;

int main (int) {
    cout << "This will print to the console!" << endl; // I don't know how to make it read all of the output
}

我的目标是将控制台的整个输出放入我选择的文本文件中。 (地址.txt)

【问题讨论】:

  • 不相关:myfile &lt;&lt; printf &lt;&lt; endl; 很可能会导致人们因重复使用 printf 而抓狂。除非你真的想打印printf 函数。在那种情况下,为什么?
  • 将 C++ 抛在后面并在命令行中使用重定向可能会更简单:MyProgram &gt; myfile.txt

标签: c++ console


【解决方案1】:

当您调用myfile &lt;&lt; printf &lt;&lt; endl 时,您不会从控制台获取文本,而是获取函数的标识符。要从控制台获取文本,请查看 std::cin ex。

int x;
std::cin >> x;
std::cout << "You Entered: " << x << std::endl;

旁注,请避免使用using namespace,这会使代码更容易阅读,因为它可以清楚地表明它是您的函数还是其他库的

【讨论】:

    猜你喜欢
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多