Creating String From A Loop
Dear all,
I tried to create a string with this code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include <fstream>
#include <string>
#include <stdio>
#include <stdlib>
#include <vector>
using namespace std;
int main () {
vector <vector<string> > numTag;
for (int tagno=0; tagno <=10; tagno++) {
//here we want to create a string out of
// this loop
for (int j=0; j <=5; j++) {
numTag.push_back(j);
}
cout << "Tag No: " << tagno << ",is " << numTag << endl;
}
}
|
The expected results is this:
1 2 3 4
|
Tag No: 1, is 012345
Tag No: 2, is 012345
...
Tag No: 10, is 012345
|
But not sure why the code fails?
You are trying to push_back() an integer where a vector of strings is expected.
Perhaps you are thinking something like (highly simplified for clarity):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector <string> tag_list;
// Create the list of tags
for (int tag_idx = 0; tag_idx < 20; tag_idx++)
{
ostringstream oss;
oss << "tag_" << setfill( '0' ) << setw( 2 ) << tag_idx;
tag_list.push_back( oss.str() );
}
// Show them to the user
copy(
tag_list.begin(),
tag_list.end(),
ostream_iterator <string> ( cout, "\n" )
);
return 0;
}
|
Hope this helps.
Topic archived. No new replies allowed.