First word not being processed correctly.......not urgent.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • whodgson
    Contributor
    • Jan 2007
    • 542

    First word not being processed correctly.......not urgent.

    The following code accepts a string from the user and swaps the first and last letters in each word. It prints out the original string incorrectly by dropping off the first letter of the first word. I would like to establish what error in the code is causing the first word to be mangled.
    Code:
    #include<iostream>
    #include<cstring>
    #include<cstdlib>
    using namespace std;
    
    int main()
    {
    cout<<"Transposing letters in a string \n";
    cout<<"Type a short sentence (end with Ctrl+Z)"<<endl;
    char s[81]={0};
    int count=0;
    do
    {
    cin.getline(s,81);
    //if(*s)cout<<s;  //this prints the sentence correctly
    }while(*s);
    
    for(int i=0;i<sizeof(s);i++)        
    { 
      cout<<s[i];
      if(s[i]==' ')count++;
    } 
    cout<<"\nThere are "<<count<<" words in the sentence\n";
    
    char *p1=&s[0];          //set both pointers to 1st letter
    char *p2=&s[0];
    while(*p2>='a' && *p2<='z' || *p2>='A' && *p2<='Z' )
           { p2++; }         // advance p2 to end of 1st word
            if(*p2==' ')
            p2--;  
           swap(*p1,*p2);
        
        for(int i=0;i<count;i++)//remaining  words 
         { p2+=2;           //position p2 on 1st letter of next word
           p1=p2 ;          // move p1 to same position
           while(*p2>='a' && *p2<='z' && *p2!='\n')
           { p2++;  }       // advance p2 to end of next word
           if(*p2==' ')p2--;//if it goes to space..bring back one
           swap(*p1,*p2);        
           
        }
    cout<<"After swapping, the string becomes: \n";   
       
    for(int i=0;i<sizeof(s);i++)        
    {  
      cout<<s[i]; 
    }   
    cout<<"\n\n";
    char q;    
    cout<<"Press any key to continue...";
    cin>>q;
    
    return 0;
    }
    /*
    Transposing letters in a string
    Type a short sentence (end with Ctrl+Z)
    Swapping the first and last letter in each word ^Z

    wapping the first and last letter in each word
    There are 9 words in the sentence
    After swapping the string becomes:
    wgppina eht tirsf dna tasl rettel ni hace dorw

    Press any key to continue...
    */
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    When you type ^Z and press enter, you while loop is terminated and 0 is stored at the first element of s, overwriting the first letter.

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      Many thanks........I looked at about 15 possible causes but that wasn`t one of them.....althou gh i did notice that the space between the first and second word was sometimes wider. Anyway I can now do something about it.....thanks again newb16.

      Comment

      Working...