0

ここで役立つ回答を得た後、さらに別の問題に遭遇しました。表示したい列に2つ以上の文字列を表示することです。私が抱えている問題の例として、次の出力が必要です:

Come here! where?             not here!

しかし、代わりに得る

Come here!                     where? not here!

コードを使用するとき

cout << left << setw(30) << "Come here!" << " where? " << setw(20) << "not here!" << endl;

両方の列の幅に 2 つの文字列を含めることができることを確認しました (と思います) が、列の幅をどれだけ大きく設定しても、エラーは依然として存在します。

4

3 に答える 3

3

setw()のみが次に出力される文字列をフォーマットするため、複数の連続した文字列ではなく、各列の内容を単一の文字列として出力する必要があります。そのため、印刷する前に文字列を連結する必要があります。たとえばstring::append()、またはを使用し+ます。

cout << left << setw(30) << (string("Come here!") + " where? ") << setw(20) << "not here!" << endl;
于 2010-03-12T22:28:10.460 に答える
2

述べたようsetw()に、次の入力にのみ適用され、2 つの入力に適用しようとしています。

リテラル定数の代わりに変数を使用する機会を与える他の提案に代わるもの:

#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;

int main()
{
    stringstream ss;
    ss << "Come here!" << " where?";
    cout << left << setw(30) << ss.str() << setw(20) << "not here!" << endl;
    return 0;
}
于 2010-03-12T22:34:58.833 に答える
1

setw次の文字列のみをカバーするため、それらを連結する必要があります。

cout << left << setw(30) << (string("Come here!") + string(" where? ")) << setw(20) << "not here!" << endl;
于 2010-03-12T22:29:21.600 に答える