例如,我使用以下命令从用户那里获得输入std::cin
:
"This is a sample program"
我想用另一个字符替换每个空格并将其显示回来,如下所示:
"This\is\a\sample\program"
注意:其他字符可以是任何字符。例如:*
或&
或$
等。
我想使用流操纵器来做到这一点。可能吗?
这是我尝试使用 std::getline 的一些示例代码,但这不是我期望的那种代码。我想使用任何现有的i/o stream Manipulators
或我自己的操纵器来做到这一点。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string spaceToStar(string text){
for (int i=0;i<sizeof(text);i++){
if(text[i] == ' ')
text[i] = '*';
}
return text;
}
int main () {
string text, s;
cout << "enter your line: " << endl;
getline(cin, text);
s = spaceToStar(text);
cout << s << endl;
return 0;
}