Kelly
Kelly

Reputation: 213

Replacing spaces in a string by %20 in C++

#include <iostream>
#include <string>

void removeSpaces(std::string );

int main()
{
        std::string inputString;
        std::cout<<"Enter the string:"<<std::endl;
        std::cin>>inputString;

        removeSpaces(inputString);

        return 0;
}



void removeSpaces(std::string str)
{
        size_t position = 0;
        for ( position = str.find(" "); position != std::string::npos; position = str.find(" ",position) )
        {
                str.replace(position ,1, "%20");
        }

        std::cout<<str<<std::endl;
}

I am not able to see any output. For example

Enter Input String: a b c
Output = a

What's wrong?

Upvotes: 2

Views: 2220

Answers (3)

sachin
sachin

Reputation: 203

another better way to do is to count no of spaces, create new string of length = old length +2*count and start moving characters from old string to new string except for a space replace it with %20....

Implementation http://justprogrammng.blogspot.com/2012/06/replace-all-spaces-in-string-by-20.html

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283624

std::cin>>inputString;

stops at the first space. Use:

std::getline(std::cin, inputString);

instead.

Upvotes: 9

Chad
Chad

Reputation: 19032

cin by default stops at whitespace.

Change your input to:

// will not work, stops on whitespace
//std::cin>>inputString;

// will work now, will read until \n
std::getline(std::cin, inputString);

Upvotes: 5

Related Questions