C++ Help!

W

whitedragon007

Hi I'm trying to print "Spiderman is amazing" twice but on the secon
line, it is giving me some weird symbols. Can someone please help m
fix this problem... Thanks...


#include <iostream.h>
main()
{
char mynameis[]="Spiderman is amazing";
char string[25];
char *ptr=mynameis;
char *p=string;
for(int i=0; mynameis !='\0'; i++)
*p = *ptr;
cout<<ptr<<'\n';
cout<<p<<'\n';

return 0;



-
whitedragon00
 
E

Emad Barsoum

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
 
D

David Olsen

whitedragon007 said:
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...

#include <iostream.h>
main()
{
char mynameis[]="Spiderman is amazing";
char string[25];
char *ptr=mynameis;
char *p=string;
for(int i=0; mynameis !='\0'; i++)
*p = *ptr;
cout<<ptr<<'\n';
cout<<p<<'\n';

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.
 
P

Patrick Kowalzick

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.

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 !='\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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top