Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Some help with string and char* please

Status
Not open for further replies.

MatthiasE

Programmer
Oct 19, 2004
5
US
Why does the following code not work? It compiles just fine, but s doesn't seem to take.

I want to copy the string str to char* s.


string str;
char* s=" ";

cout<<"\nEnter String: ";
cin>>str;
int len = str.size();

for(int j=0; j<len; j++)
{
if(str[j] >= '0' && str[j] <= '9' || str[j] == '.')
{
*s++ = str[j];

}
}
 
For one thing, you never allocate any memory for s. For another, you're trying to write over your string literal " ". For another, you use char* to point to a const char*. For another, you never attempt to null-terminate your char*.

Try:
Code:
cout<<"\nEnter String: ";
cin>>str;

char* s = new char[ str.size() ];

// copy characters to s and null-terminate it

> I want to copy the string str to char* s.

Seems like your code would only be copying digits and periods.
 
Code:
char* s = new char[ str.size()[COLOR=red]+1[/color] ];
The string size does not include a null terminator, so your char* must have one extra character.
 
You can also use the isdigit() function to replace str[j] >= '0' && str[j] <= '9', and that should make your code look cleaner.
 
and instead of using that for loop to copy one char at a time, use strcpy().
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top