This has been boggling me, the simple code:
int main()
{
typedef std::string::size_type stype;
std::cout << "What is your first name?\n";
std::string first,second,fullname;
std::cin >> first;
std::cout << "What is your second name?\n";
std::cin >> second;
char * backwards;
fullname = first + " " + second;
stype fnsize = fullname.size();
backwards = new char [fnsize];
stype b = 0;
for(stype a = fnsize; a != 0; --a)
{
backwards[b++] = fullname[a - 1];
}
std::cout << backwards << std::endl;
return 0;
}
Works most of the time, but when I write a name like my own, stanislaw terziev, I get an output veizret walsinatsslaw instead of veizret walsinats
Why is it so?
Two problems in your code.
First, you want
backwardsto befnsize + 1to allow for the end of string termination (required for a C-style string, not included in thestd::string::size()method return value).Second, make the last element of
backwardsa'\0'character (the end of string character). Without this,std::coutdoes not know where the char* ‘ends’ so you will sometimes get garbage characters. That is to say std::cout will keep outputting characters until it hits a'\0'.A couple of other options you could look at as well:
std::stringand useappend(fullname[a-1])std::reverse