question on whitespace in string

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

    question on whitespace in string

    I am writing a program that takes input from a user and the program corrects the whitespace and capitalization errors. I have written the part to get the input from the user and stores it in an string with a getline function. My problem is I am tring to figure out a way to check and remove whitespace if anyone can help

    thanks

    Code:
    #include <string>
    #include <iostream>
    using namespace std;
    
    int main() {
    
            cout << "enter sentence and hit enter";
            string  s1;
            getline(cin,s1);
    this is how i am getting the input in.
  • vninja
    New Member
    • Oct 2006
    • 40

    #2
    are you looking to get rid of the whitespace before the string or throughout?
    for case one you could just add a cin >> fistword; then after the getline st = firstword + st1;
    for the second case i'm not too sure....

    Comment

    • horace1
      Recognized Expert Top Contributor
      • Nov 2006
      • 1510

      #3
      Depends on what you are trying to. You could go thru your string examining each character for correct capitalisation and removing excess whitespace

      the C++ <string> class has methods which enable you to iterate thru the contents of a string, repace characters, erase characters, etc. see
      http://www.cppreferenc e.com/cppstring/index.html

      Comment

      • wyatt822
        New Member
        • Jan 2008
        • 1

        #4
        I have had success deleting all whitespace from a given string using the following:

        1 #include <iostream>
        2
        3 void DeleteWS(std::s tring& x)
        4 {
        5 for(unsigned int i = 0; i <= x.length(); i++)
        6 {
        7 if(x[i] == ' ')
        8 {
        9 x.erase(i, 1);
        10 }
        11 }
        12 }
        13 int main()
        14 {
        15 std::string myString;
        16 std::cout << "String: ";
        17 getline(std::ci n, myString);
        18 DeleteWS(myStri ng);
        19
        20 std::cout << myString << std::endl;
        21 }

        If anybody notices anything inherently wrong with this code, please let me know.

        Comment

        Working...