Groups | Blog | Home
all groups > visual c > june 2004 >

visual c : C++ Help!


whitedragon007
6/26/2004 1:58:22 PM

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[i] !='\0'; i++)
*p = *ptr;
cout<<ptr<<'\n';
cout<<p<<'\n';

return 0;



-
whitedragon00
-----------------------------------------------------------------------
Posted via http://www.codecomments.co
-----------------------------------------------------------------------
Emad Barsoum
6/26/2004 2:44:04 PM
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

"whitedragon007" <whitedragon007.18h75m@mail.codecomments.com> wrote in
message news:whitedragon007.18h75m@mail.codecomments.com...
[quoted text, click to view]

David Olsen
6/26/2004 9:07:02 PM
[quoted text, click to view]

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.

--
David Olsen
qg4h9ykc5m@yahoo.com
Patrick Kowalzick
6/28/2004 5:10:20 PM
Hello,

[quoted text, click to view]

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:

[quoted text, click to view]

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

[quoted text, click to view]

should be "int main()"

[quoted text, click to view]

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.

[quoted text, click to view]

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

AddThis Social Bookmark Button