c++ - 如何使用输入和输出流操纵器将所有空白字符替换为另一个字符?

标签 c++ c++11 c++14 manipulators

例如,我使用 std::cin 从用户那里获得输入:

“这是一个示例程序”

我想用另一个字符替换每个空格并将其显示回来:

"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;
}

最佳答案

您可以在字符通过流缓冲区时替换它们,并创建一个用于简化语法的操纵器。这是一种方法,可能不是最好的实现方式,但它确实有效。

#include <iostream>
#include <memory>
using namespace std;

namespace xalloc {
  int from(){static int x=std::ios_base::xalloc();return x;}
  int to(){static int x=std::ios_base::xalloc();return x;}
}

template<class cT>
struct filterbuf : std::basic_streambuf<cT> {
  std::basic_streambuf<cT>* sbuf;
  std::ios_base& ios;
public:
  filterbuf(std::basic_ostream<cT>& str) : sbuf(str.rdbuf()), ios(str) {}
  int overflow(typename filterbuf::int_type c) {
      if (filterbuf::traits_type::eq_int_type(c, ios.iword(xalloc::from()))) {
          return this->sbuf->sputc(ios.iword(xalloc::to()));
      }
      return this->sbuf->sputc(c);
  }
  int sync() { return this->sbuf->pubsync(); }
};


template<class cT>
struct reinterpret { 
  cT from, to;
  template<class T>reinterpret(T f, T t) : from(f), to(t) {}
};

std::basic_ostream<cT>& operator<<(std::basic_ostream<cT>& os, reinterpret rt) {
  static auto nofree=[](std::streambuf*){};
  static std::unique_ptr<filterbuf<cT>, decltype(nofree)> buffer(
    new filterbuf<cT>(os),nofree
  );
  os.iword(xalloc::from()) = rt.from;
  os.iword(xalloc::to()) = rt.to;
  if (os.rdbuf() != buffer.get()) os.rdbuf(buffer.get());
  return os;
}

template<class T>
reinterpret(T, T) -> reinterpret<T>;


int main() {
  cout << reinterpret(' ', '\\') << "A B C D\n"; // A\B\C\D
  cout << reinterpret(' ', '*') << "A B C D\n"; // A*B*C*D
}

关于c++ - 如何使用输入和输出流操纵器将所有空白字符替换为另一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56652333/

相关文章:

c++ - 有关如何创建 NSIS 插件的资源

c++ - 静态存储持续时间初始化

c++ - 尽管一切看起来都正确,为什么 boost::serialize 不起作用? ("unregistered class")

c++ - 为什么指向 int 的指针转换为 void* 而指向函数的指针转换为 bool?

c++ - 通过 std::enable_if_t 传递被调用方法的返回值

c++ - 如何在 c++ "XY:56:21AM"中从这个字符串中分离出 HH、MM、SS 和 merdian?以下程序出现段错误

c++ - std::move() 之后 std::vector 存储会发生什么

c++ - 编译器支持 STL 容器中的有状态分配器

QThread 和 C++11 lambda : wait for finished

c++ - 为什么异常捕获是基于顺序的而不是基于最接近的继承?