Hi,
The p pointer doesn't have a null at the end of the string, you copy
each character and left the null to terminate the string.
Regards,
Emad
> Hi I'm trying to print "Spiderman is amazing" twice but on the second
> line, it is giving me some weird symbols. Can someone please help me
[quoted text clipped - 20 lines]
> Posted via http://www.codecomments.com
> ------------------------------------------------------------------------
> Hi I'm trying to print "Spiderman is amazing" twice but on the second
> line, it is giving me some weird symbols. Can someone please help me
[quoted text clipped - 14 lines]
> return 0;
> }
1. You aren't copying the '\0' at the end of the string. The loop
bails out as soon as the '\0' is encountered, before it can be copied.
2. You aren't copying anything at all past the first character. "p"
and "ptr" are never changed, so the 'S' is copied twenty times. So
string[0] is 'S' and the rest of the characters in string are garbage.

Signature
David Olsen
qg4h9ykc5m@yahoo.com
Hello,
> Hi I'm trying to print "Spiderman is amazing" twice but on the second
> line, it is giving me some weird symbols. Can someone please help me
> fix this problem... Thanks...
Try this one:
// code start
#include <iostream>
#include <string>
int main()
{
std::string mynameis = "Spiderman is amazing";
std::string iamnoname = mynameis;
std::cout << mynameis << std::endl;
std::cout << iamnoname << std::endl;
return 0;
}
// code end
and some comments from my side:
> #include <iostream.h>
<iostream.h> does not exist in C++. If it works, it is just for backward
compatibility. Use instead <iostream>. Bear in mind that most functions,
types, definitions,... are then embedded in the "std" namespace.
Try to avoid a global "using namespace std" which may result in conflicts.
> main()
should be "int main()"
> {
> char mynameis[]="Spiderman is amazing";
> char string[25];
string is not a nice name here, because string is a class defined in the C++
Standard. You may use it, but it may be confusing.
> char *ptr=mynameis;
> char *p=string;
> for(int i=0; mynameis[i] !='\0'; i++)
Just for the habits. There is no difference in the loop when you use i++ for
built-in types but the post-increment calls the pre-increment in many
classes. So, just use always ++i in loops and you are fine.
Regards,
Patrick