Previous Page

Remove white spaces, or anything, from a string input
C++ console

Copy and Paste the following code into your favorite C++ Integrated Development Environment (IDE) - compile and run.


#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str; // variable for user's input
    int size;   // variable to store size of the string

    cout << "Enter a sentence to remove all white spaces from it: "
         << endl;// instruct user what to enter

    getline(cin, str);// get user's sentence

    size = str.size();// size of the string

/***************************************************************************************************/

    for (int i = 0; i < size; i++) // this for loop removes the unwanted characters you choose
    {
        if (str[i] == ' ')// if the string contains a white space.
                          // NOTE: whatever you want to remove put inside the single
                          //       quotes as an argument. Use the OR symbol to enter
                          //       multiple arguments.
                          // For Example:
                          //       if (str[i] == '.' || str[i] == ':' || str[i] == '6')
                          // This would remove all periods, colons, and 6s.

        { // start if statement
            str.erase(i,1); // erases the unwanted character from the string, 1 character
                            // at a time.
            i--;// this makes sure multiple spaces in-a-row are removed.
        } // end if statement
        
    } // end for statement
    
/***************************************************************************************************/

    cout << str << endl;// output the user's sentence without white spaces

   return 0;

}// END MAIN

//END OF CODE