【问题标题】:Option to print output to screen or given file name (c++)将输出打印到屏幕或给定文件名的选项(c++)
【发布时间】:2020-04-08 03:00:57
【问题描述】:

我希望选项 2 将输出传递给键入的文件名。但是,程序正在创建文件,但没有将输出传递给文件。我认为在这里只使用 ostream 就可以了,但不知道该怎么做。

void displayTable(int n, char op) {
    int printOption;
    string outputFileName;
    ofstream createOutputFile;

    while (true) { //option for print screen or print to file
        cout << "Select: \n1) Print on Screen \n2) Print to a file name \nSelection: ";
        cin >> printOption;

        if (printOption == 1)
            break;
        else if (printOption == 2){
            cout << "Type in the name for the output file." << endl;
            cin >> outputFileName;
            createOutputFile.open(outputFileName);
            break;
        }
        else
            cout << "Please enter a valid number." << endl;
    }

    int max = getMaxSize(n, op);
    cout << setw(max) << op << "|";
    for (int i = 1; i <= n; ++i) {
        cout << setw(max) << i;
    }
    cout << endl;
    for (int i = 0; i < max; ++i) {
        cout << "-";
    }
    cout << "+";
    for (int i = 0; i < n * max; ++i) {
        cout << "-";
    }
    cout << endl;
    for (int i = 1; i <= n; ++i) {
        cout << setw(max) << i << "|";
        for (int j = 1; j <= n; ++j) {
            cout << setw(max) << getValue(i, j, op);
        }
        cout << endl;
    }

    cout << endl;
    createOutputFile.close();
}

【问题讨论】:

  • 这个问题中显示的代码不符合stackoverflow.com对minimal reproducible example的要求,因此这里的任何人都不太可能最终确定问题,而最多只能猜测.这个问题必须是edited 以显示一个最小示例,不超过一两页代码(“最小”部分),任何人都可以剪切/粘贴、编译、运行和重现所描述的问题(“可重现”部分)完全如图所示(这包括任何辅助信息,例如程序的输入)。请参阅How to Ask 了解更多信息。

标签: c++ file


【解决方案1】:

您没有将任何内容打印到createOutputFile,而是将所有内容打印到cout。这就是为什么看不到文件中的任何内容以及控制台中的所有内容的原因。

解决问题的最简单方法是将cout 重定向到createOutputFile 的输出缓冲区,例如:

auto cout_buff = cout.rdbuf();
...
createOutputFile.open(outputFileName);
cout.rdbuf(createOutputFile.rdbuf())
// all cout outputs will now go to the file...
...
cout.rdbuf(cout_buff); // restore when finished...

否则,请将您的打印逻辑移至以ostream&amp; 作为参数的单独函数:

void doMyLogic(ostream &os)
{
    // print to os as needed...
}

...

if (printOption == 1) {
    doMyLogic(cout);
    break;
} 
if (printOption == 2) {
    ...
    ofstream createOutputFile(outputFileName);
    doMyLogic(createOutputFile);
    break;
}
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 2023-04-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多