2011-09-12 42 views
2
#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; 
} 

我无法看到任何输出。例如在C++中用%20替换字符串中的空格

Enter Input String: a b c 
Output = a 

怎么了?

+0

可能重复不能在字符串中使用? C++](http://stackoverflow.com/questions/4992229/spaces-cant-be-used-in-string-c) –

回答

9
std::cin>>inputString; 

停在第一个空格处。使用:

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

改为。

+0

在调用'removeSpaces()'之前调用一个小诊断输出将在问题出现之前解决这个问题甚至有必要... –

+0

工作:)。谢谢 – Kelly

5

cin默认停在空白处。

更改您的输入:

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

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