#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;
}
我无法看到任何输出。例如
Enter Input String: a b c
Output = a
怎么了?
答案 0 :(得分:9)
std::cin>>inputString;
停在第一个空间。使用:
std::getline(std::cin, inputString);
代替。
答案 1 :(得分:5)
cin
会在空格处停止。
将您的输入更改为:
// will not work, stops on whitespace
//std::cin>>inputString;
// will work now, will read until \n
std::getline(std::cin, inputString);
答案 2 :(得分:0)
另一个更好的方法是计算空格数,创建长度=旧长度+ 2 *计数的新字符串并开始将字符串从旧字符串移动到新字符串,除了空格用%20替换它....
<强>实施强> http://justprogrammng.blogspot.com/2012/06/replace-all-spaces-in-string-by-20.html