question with strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gdarian216
    New Member
    • Oct 2006
    • 57

    question with strings

    I am writting a program that gets a line of input from a user and puts that in a string. Then it needs to correct whitespace and capitalization. If there is more then one space of whitespace between words change it to one space and if it is a period add a space.

    this is what i have so far and Im trying to get the whitespace right.


    Code:
    #include<string>
    #include<iostream>
    using namespace std;
    
    int main() {
    
            cout << "enter sentence and hit enter";
            string  s1;
    
            getline(cin,s1);
    
             if(s1 != " ");
            {
    
                    char seporator = ' ';
                    if (s1[s1.length()-1] == '.')
                    { seporator = '\n';
                    }
    
                    cout << s1 << seporator;
                    }
    
            while(s1 != " ");
    
            return(0);
    
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You have you loop wrong, you need to be looping down the string checking each character. For each character you will probably need to set some flags, was it a space?, do you need to capital ise the next character.

    Then as you read each character you can use the flags to take appropriate action

    Code:
    LastCharacterWasSpace = false
    LastCharacterRequiresSpace = false
    CapitaliseNextNonSpace = true
    
    
    FOREACH Character IN String
        IF Character Is Space
            IF LastCharacterWasSpace = true
                REMOVE Character FROM String
            ELSE
                LastCharacterWasSpace = true
                LastCharacterRequiresSpace = false
            ENDIF
        ELSE // Character is not space
            IF LastCharacterRequiresSpace
                INSERT Space INTO String
                LastCharacterRequiresSpace = false
            ENDIF
    
            LastCharacterWasSpace = false
    
            IF Character = FullStop
                LastCharacterRequiresSpace = true
                CapitaliseNextNonSpace = true
            ELSE IF Character = Comma
                LastCharacterRequiresSpace = true
            ELSE
                IF CapitaliseNextNonSpace = true
                    Character = UpperCase( Character )
                ELSE
                    Character = LowerCase( Character )
                ENDIF
                CapitaliseNextNonSpace = false
            ENDIF
        ENDIF
    ENDFOR

    Comment

    Working...