简体   繁体   English

将 output 打印到屏幕或给定文件名的选项(c++)

[英]Option to print output to screen or given file name (c++)

I would like option 2 to pass the output to a typed file name.我希望选项 2 将 output 传递给键入的文件名。 However, the program is creating the file but not passing the output to the file.但是,程序正在创建文件,但没有将 output 传递给文件。 I think just using ostream is fine here, but don't know how to go about it.我认为在这里使用 ostream 很好,但不知道如何 go 关于它。

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();
}

You are not printing anything to createOutputFile , everything is being printed to cout instead.您没有将任何内容打印到createOutputFile ,而是将所有内容打印到cout That is why to don't see anything in the file, and everything in the console.这就是为什么看不到文件中的任何内容以及控制台中的所有内容的原因。

The easiest way to solve your issue is to redirect cout to createOutputFile 's output buffer, eg:解决问题的最简单方法是将cout重定向到createOutputFile的 output 缓冲区,例如:

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...

Otherwise, move your print logic to a separate function that takes an ostream& as a parameter:否则,将您的打印逻辑移动到以ostream&作为参数的单独 function :

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

...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM