How manipulate a string?

Hi, i'm difficults for manipulate a string! I want that stay so:

sexozin_001
sexozin_002
sexozin_003
sexozin_004
sexozin_005
....
sexozin_031

My code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
string sexo = "sexozin_000";

for(int i = 1; i <= 31; i++){
sexo[11] = i;
cout << sexo << endl;
}

return 0;
}
In future please use [ Code] [ /Code] tags.

You can't just use 1 index on the string because you don't know how long the number will be. There are a few ways to do this but here is 1 example. to_string is C++11 but you can look up other functions if you are stuck on C++03.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string sexo = "sexozin_000";

    for(int i = 1; i <= 31; i++)
    {
	   string S = to_string(i);

           // go back 1 or 2 from the end depending on how long the number is 
	   sexo.replace(sexo.end() - S.length(), sexo.end(), S);   
	
           cout << sexo << endl;
    }

   return 0;
}


http://www.cplusplus.com/reference/string/string/replace/
http://www.cplusplus.com/reference/string/to_string/
to_string is C++11 but you can look up other functions if you are stuck on C++03.

Either get Code Blocks using C++11 (I don't use it, but there is tons of info online) or you will have to use an older method to get int to string, like stringstream.
http://www.cplusplus.com/articles/D9j2Nwbp/
Topic archived. No new replies allowed.