| re: Please help: swap char problem in c++
On 11 Oct 2005 00:29:06 -0700, "dbuser" <ranjanr@gmail.com> wrote:
[color=blue]
>Hi,
>I have to implement every even and odd character swapping of a stream.
>My problem is with the following code is that if the stream has total
>even no of characters in it(including spaces) then it works, but when
>it has odd no of characters, then last characters is not written ,
>because it does not have i+1 element to swap. Here is what I am doing:
>Please suggest the correct way of doing this for any number of
>character.
>void swap( char * w) //array is read from a file and passed here.
>{
> int i,len = strlen(w);
> for ( i=0; i<len; i=i+2) {
> swapchar( &w[i], &w[i+1]);
> }
>
> cout << "swapped :" << w << endl;
>}
>void swapchar( char * c1, char * c2)
>{
>char temp=*c1; *c1=*c2; *c2=temp;
>}
>
>Thanks very much for help ![/color]
No, it is not that last char is not written but that last char is
swapped with teminating '\0', thus cutting the string.
Use, for instance, the following loop instruction instead of yours
for ( i=0; i<len-1; i=i+2) {
By testing this way, last char will not be swaped when length is odd |