I’ve got a character from the keyboard, by integer:
int c = getch();
an I want to append it to a string only if it isn’t a return:
void somefunction()
{
std::string str = "you pressed: ";
int c;
while ( 1 )
{
c = getch();
if ( c == 10 ) break;
char* ch;
sprintf(ch,"%c",c);
str += std::string(ch);
}
}
however, this creates a segmentation error when the scope of somefunction is left. I’m geussing that when the dtor for str is called the pointer to ch isn’t available any more.
How can I remedy this?
You are getting segmentation fault, because you are trying to
sprintfstring into unknown (not yet allocated) memory:possible fix of your code would be to replace
char* ch;withchar ch[2];which would causechto become an statically allocated array with an automatic storage duration.But note that since you are programming in C++ it would be wiser to use streams and methods of
std::stringrather than C-style (char*) strings and C-style functions likesprintf.