2011-09-12 12 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デフォルトでは、空白で止まります。

にご入力を変更し

:行うには、別の良い方法はカウントして、新しい文字列に古い文字列からの移動を開始*、スペースのないを数える長=古い長さ+ 2の新しい文字列を作成することはありません

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

// will work now, will read until \n 
std::getline(std::cin, inputString); 
関連する問題