problem with string

Hello friends,

well, actually i dont like the title ...

But, i have the code below :

1
2
3
4
5
6
7
8
char temp[200] = "I am from Jupiter"
string useful ; // the useful is the word "Jupiter"
				
int maxle = 0 ; 
maxle = strlen(temp); //max length temp 
				
for(int i=0; i<maxle; i++)
     useful[i] = temp[10+i] ;


and my problem is that if you try :

cout << useful ;

you will have no answer! The compiler does not recognize the useful like string but char . Any help, please .

Also, is it possible to avoid the for-loop ?


Thank you.
1
2
for(int i=0; i<maxle; i++)
     useful[i] = temp[10+i] ;


This is "very bad". Just like arrays, if you use [] to access beyond the boundaries, you corrupt memory. Note you cannot add new characters with the [] operator. You can only read/modify existing ones.

In this case, since 'useful' contains an empty string, everything is an out-of-bounds access.

Also, is it possible to avoid the for-loop ?


Yes. Just use the assignment operator:

 
useful = temp+10;
Thank you very much DISCH , the code you provide works perfect:

useful = temp+10 ;

I would like to ask, because i cannot determine it, will the string useful be

1) "Jupiter"

OR

2) "Jupiter "

(the second is with a space at the end)

If it is the 2nd, how can i avoid it ?

If not, generally if i have a string with a space at the end is it possible to "delete" the space ?
Yeah it possible just:
Add #include<string>
then use trim(yourstring); function to remove space.
I think will help
Last edited on
i use the code :

trim(useful) ;

including the string header but i receive the error :

`trim' was not declared in this scope

Also i tried the code below :

remove(useful.begin(), useful.end(), ' ') ;

but it does not delete the space at the end of the string ...

Any suggestion ?
Last edited on
 
remove(useful.begin(), useful.end(), ' ') ;


Are you using the algorithm remove function ?

Based on http://www.cplusplus.com/reference/algorithm/remove/ there is this line "Notice that this function does not alter the elements past the new end, which keep their old values and are still accessible."

So it seems remove function does NOT remove elements. All it does is to push those to be deleted to the end. To truly delete those is to call the erase method of the container classes you are using.
Thanks sohguanh, i did not notice that reference .

i am trying

 
useful.erase(useful.end()) ;


but it is not working, the terminal or cmd "freezes" . If i am right, i must convert string to vector ?
Is this posible with casting ?
Last edited on
Topic archived. No new replies allowed.