2017-11-22 2 views
0

は、このデータを使用して...

for(int i = 0; i < array.size(); i++) 
{ 
    string name; 
    int number; 

    if (array[i] == 0) 
    { 
    name ="jack"; 
    number="10"; 
    } 
    else if (array[i] == 1) 
    { 
    name="alice"; 
    number=15"; 
    } 
    //.... 
} 

のiは0,1,2,3のような未知のサイズの配列を持っているとしましょうベクトルデータに基づいて文字列を生成する私のような文字列を生成したいと思います:

string text = name(number)+name(number)+name(number)... 

は、どのように私は、このためのコードを記述しないでください

文字列

にarray.size()回名(番号)がなければなりませんか?

+0

ルック。 –

+0

ループの前に空の文字列を初期化し、すべての反復であなたの名前と番号を追加するだけです。 + = name + "(" + to_string(number)+ ")"というテキストを書くことができます。 –

答えて

0

使用にstringstream

#include <iostream> 
#include <string> 
#include <sstream> 
#include <utility> 

int main() 
{ 

    std::vector<std::pair<std::string, int>> array; 
    array.push_back(std::make_pair("jack", 10)); //index 0 
    array.push_back(std::make_pair("alice", 15)); //index 1 
    array.push_back(std::make_pair("bob", 20)); //index 2 

    std::ostringstream oss; 
    for (auto &el : array) 
    { 
     oss << el.first << "(" << el.second << ")"; 
    } 

    std::string text = oss.str(); 
    std::cout << text; 

    return 0; 
} 

プリント: `のstd :: ostringstream`で

jack(10)alice(15)bob(20) 
0

あなたはstd::ostringstreamを使用することができます。

std::ostringstream out_stream; 
out_stream << name << "(" << "number" << ")"; 
//... 
std::cout << out_stream.str() << std::endl;