2011-11-07 14 views
7

テキストstd :: coutと同様の方法で文字列を作成できますか?

std::cout << "Hi, my name is " << name_as_string << " and I am " << age_as_int << " years old, while weighing " << weight_as_double << " kilograms."; 

の単一の文字列としてコンソールに次の文パイプ出力のすべての種類は、我々は文字列変数に文字列を構築するために、この同じ構文を使用することはできますか?どうしたの?

答えて

10
#include <sstream> 

std::ostringstream ss; 
ss << "Hi, my name is " << name_as_string; 
ss << " and I am " << age_as_int << " years old, while weighing "; 
ss << weight_as_double << " kilograms."; 

std::string str = ss.str(); 

また、入力と出力の両方のための複数の入力のためのstd::istringstream、およびstd::stringstreamを使用することができます。

std::string str = "1 2 3 4 5"; 
std::istringstream ss(str); 
int i; 
while(ss >> i) { 
    std::cout << i; 
} 
+0

は、技術的には 'のstd :: ostringstream'はよりaddecuateだろう。 –

+0

私はstdに行くことができないことは残念です:: string str = ss;最後の行におそらく良い理由がある、あなたはそれが何であるか知っていますか? –

+3

@BillForster:暗黙の変換は危険なことがあり、しばしば望ましくありません。 – GManNickG

2

stringstreamはあなたを救助します。 std::stringstreamを使用することにより

#include <sstream> 

std::stringstream ss; 

ss << stuff << to << output; 

std::string s = ss.str(); 
1

#include <sstream> 
#include <iostream> 

int main() 
{ 
    std::stringstream ss; 
    ss << "Hi, my name is " << name_as_string << " and I am " << age_as_int << " years old, while weighing " << weight_as_double << " kilograms."; 
    std::cout<<ss.str()<<std::endl; 
} 
関連する問題