Thursday, July 30, 2009

How to copy a character into a string in c++ ?

if I have have char letter; and char word[5]; and I want the letter in char letter to add itself in the end of the word of word[5]...


if I just use strcat(word,letter); it will give me an error cuz it cant convert from char to char[5], so how can I solve that?

How to copy a character into a string in c++ ?
strcat takes two strings, not a string and a character.





You can append a letter to the end of a string. There is a potential problem. If all the characters in the array word are used, it doesn't make sense to add another character.





char word[5] = "hope";





Here, all the elements of word are occupied. word[0] == 'h', word[1] == 'o', word[2] == 'p', word[3] == 'e', word[4] == 0. If you add a letter to the end, you will mess up the string.





If it's something smaller, then you can add like this:





char word[5] = "in";





int word_len = strlen(word);





strlen does not include the trailing 0. We have to keep track of it. For any null terminated string, string[strlen(string)] == 0 (it points to the null terminator).





word[word_len] = letter; // replace trailing 0 with new letter


word[word_len + 1] = 0; // put trailing 0 one spot later.





If you are using C++, look at the std::string class. It will make things a whole lot easier. I think students jumping into this kind of string management right away is a mistake.
Reply:have you tried a sprintf()?


No comments:

Post a Comment