0

したがって、次のような単純な対話型プログラムがあるとします。

#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#define cout os

int main() {

    stringstream os;

    cout << "If you would like to continue, type 'Continue'" << '\n';

    string line;
    while (cin >> line) {

        if (line == "Continue") {
            cout << "If you would like to continue, type 'Continue'" << '\n';
        }

        else { break; }
    }

    cout << "Program ended." << '\n';

    cout << os.str();
    return 0;
}

標準出力に出力されるすべての行が cout << os.str() によってプログラムの最後に出力されるように、ディレクティブ「#define」を含めることができるようにするにはどうすればよいですか?また、最終的な「cout」を「os」にしますか?最後にosで代わりにprintfを使用しようとしましたが、「printfへの一致する関数呼び出しがありません」というトラブル/コンパイラエラーが発生しています。

私の質問が理にかなっていることを願っています。これがすでに尋ねられている場合はお詫びしますが、ここで見つけることができませんでした.

4

2 に答える 2

2

これを達成するためにプリプロセッサマクロは必要ありません(それぞれ必要です)。印刷したいコードを関数に入れるだけです:

void writeToStream(std::ostream& os) {
    os << "If you would like to continue, type 'Continue'" << '\n';

    string line;
    while (cin >> line) {

        if (line == "Continue") {
             os << "If you would like to continue, type 'Continue'" << '\n';
        }

        else { break; }
    }

    os << "Program ended." << '\n';
}

main()必要に応じて呼び出します。

int main() {
#ifdef TOSCREEN
    writeToStream(cout);
#else
    std::stringstream os;
    writeToStream(os);
#endif
    cout << os.str();
    return 0;        
}
于 2016-03-04T18:18:19.537 に答える
0

STL の名前をプリコンパイラ定義として使用するのは悪い習慣です。をリダイレクトしたい場合は、次の方法で使用できますstd::coutstd::stringstreamstd::cout::rdbuf

#include <iostream>
#include <sstream>
#include <string>
#include <cstring>

using namespace std;

int main() {
    stringstream os;

    // redirect cout to os
    auto prv = cout.rdbuf(os.rdbuf());

    cout << "If you would like to continue, type 'Continue'" << '\n';

    string line;
    while (cin >> line) {

        if (line == "Continue") {
            cout << "If you would like to continue, type 'Continue'" << '\n';
        }

        else { break; }
    }

    cout << "Program ended." << '\n';

    // restore cout to its original buffer
    cout.rdbuf(prv);

    cout << os.str();

    return 0;
}
于 2016-03-04T18:00:47.970 に答える