用C++中的%20替换字符串中的空格

Kel*_*lly 2 c++ string

#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;
}
Run Code Online (Sandbox Code Playgroud)

我无法看到任何输出.例如

Enter Input String: a b c
Output = a
Run Code Online (Sandbox Code Playgroud)

怎么了?

Ben*_*igt 9

std::cin>>inputString;
Run Code Online (Sandbox Code Playgroud)

停在第一个空间.使用:

std::getline(std::cin, inputString);
Run Code Online (Sandbox Code Playgroud)

代替.


Cha*_*had 5

cin 默认情况下停在空白处.

将您的输入更改为:

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

// will work now, will read until \n
std::getline(std::cin, inputString);
Run Code Online (Sandbox Code Playgroud)