Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Concatinate a single char to a char*

Status
Not open for further replies.

timmay3141

Programmer
Dec 3, 2002
468
US
How do you concatinate a single char onto the end of a char*? I tried using the strcat function, but the second parameter it takes is char* so I can't just send the character. Here's an example of what I want to do:

#include <conio.h>
#include <iostream.h>

void main()
{
char* str = &quot;Entered character: &quot;;
char ch;

ch = getch();
// concatinate ch onto the end of str
cout << str << endl;
}

How do I do this?
 
well first you have to have the memory at the end of the string which you do not in your code.

next, there are any number of ways to do that, here is one:
Code:
char str[40];  // why 40? i have no idea
char ch = getch();
sprintf(str, &quot;Entered character: %c&quot;, ch);
cout << str << endl;
does that help?
-pete
 
As mentioned, there is a number of ways...

Ask yourself &quot;What is a char* ?&quot; - It is an array of chars where the last char is 0.

strlen( ) returns
* the length of the string, or put in another way
* the number of chars before the 0 char, or put in yet another way
* the index of the 0 character.

so if you want to concatenate a string with a char, simply:

.
.
int indexToZeroChar=strlen(str);
str[indexToZeroChar] = ch; // Replace the 0 char with ch
str[indexToZeroChar+1] = 0; // Set a new 0 char after the concatenated char

This assumes str is allocated to hold yet another char though...




 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top