I am writing a program now and I am typing in a lot of words through a loop and i need spaces in between each letter when they are printed out. When i type in the word i put it under word as such.. cout<<word; how can i make spaces in this word so the word printed can have s p a c e s in between each letter.
//create a string 2 times longer than mystring called newstring
//you could initialize it to 0 (if you use char array)
for(int i = 0; mystring[i] != 0; i+=2){
newstring[i] = mystring[i/2];
newstring[i+1] = ' ';
}
you can further improve these codes, so that there is no space after the last letter.
I'm sorry hamsterman but I really don't like that second idea. Strings, like all arrays, don't like to be resized. I even tried to get your code there to work with a few adjustments and it's a no go.
I guess if you knew ahead of time what the size of the input would be it could be hard coded but that's not a great suggestion.
Also for the OP, hamsterman has a typo in his first suggestion. The first idea should read:
1 2 3 4
for (int i = 0; i <= mystring.length(); i++) //Or for (int i = 0; i <= mystring.sizeof(); i++) if 'mystring' is a char array
{
std::cout << mystring[i] << ' ';
}
It would indeed be nice to know if OP was talking about c string or std::string..
@Computergeek01, what's wrong with it?
If they are char*, either newstring = newchar[strlen(mystring)+1];, or of you don't like dynamic memory, char newstring[160]; //where mystring is char[80]
If they are std::strings, string newstring(mystring.length, ' '); //and you don't need line 5 any more
oh, now I understand.. sorry, I somehow assumed you were saying that for(char* p = mystring; *p != 0; ++p) is better than for(int i = 0; mystring[i] != 0; i++)