| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Hi, I'm trying to print "Spiderman is amazing" on both lines, but on the second line, it is printing out some weird symbols before the phrase. Could someone please help correct my mistake .
Thanks. Code:
#include <iostream.h>
main()
{
char mynameis[]="Spiderman is amazing";
char string[25];
char *ptr=mynameis;
char *p=string;
for(int i=0; mynameis[i] !='\0'; i++)
*p = *ptr;
cout<<ptr<<'\n';
cout<<p<<'\n';
return 0;
}
|
|
#2
|
|||
|
|||
|
Ok first off you need to null terminate your string -
char mynameis[] = "Spiderman is amazing\0"; This lets the program know where the string ends. If you change the for loop execution line to string [i] = mynameis[i]; then you should get the desired result. Having made these observations though this code is fairly bug ridden (no offence intended but getting your head around c/c++ strings is a nightmare and the sooner someone gets you to read LOTS of tutorials the better) so I suggest you find some decent tutorials around the net and read up on how strings, pointers and arrays work in c/c++ and hopefully you'll have more luck with code like this. -KM- |
|
#3
|
||||
|
||||
|
Quote:
It is done allready. You do not need to add another 0. Quote:
you also have to copy the 0. -- julien barbier |
|
#4
|
|||
|
|||
|
When you initialize a char array with anything in double quotes. "Spider man";
A null terminator is automatically placed at the end. That is why you must make your array one element larger to allow room for the null terminator. If you chose to you place your initialization characters in single quotes, which you can do, you must add the null terminator. '\0'. Why don't you use the new ANSI standard header file <string>. Instead of char as your data type you can replace it with string and then enter you string. If I am wrong, someone punch me in the throat.... No just kidding...[img]images/icons/icon10.gif[/img] |
|
#5
|
|||
|
|||
|
Thats right but I presume the purpose of the program is to learn how that method works rather than anything else, since spiderman is indeed amazing but a program that prints this twice isn't exactly rocket science, so using string instead wouldn't help here. (Like it does everywhere else, please use it
)-KM- |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Help with C++ Pointer |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|