iostream重载__int128

本文介绍了如何为 C++ 中的 __int128 类型重载输入输出流操作符,实现高效的大整数类型输入输出。通过自定义操作符,可以简化大整数的使用过程并提高程序的可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Normal (Naive)写法,用 string(char* )

std::ostream& operator <<(std::ostream&out,const  __int128 b) {
  std::string s;  __int128 t = b;int sig = 1;
  if(t < 0) sig = -1,t = -t;
  for(;t;t/=10) s += '0' + t % 10;
  if(sig == -1) s += '-';
  reverse(s.begin(), s.end());
  if(s.length() == 0) s += '0';
  out << s ;
  return out;
}
/********* istrream 类似读入挂 O(∩_∩)O *************/

我突然有个大胆的想法系列

std::ostream& operator <<(std::ostream&out, __int128 x) {
  if(x < 0) {out << "-"; out << -x; return out;}
  if(x == 0) {out << "0"; return out;}
  if(x > 10) out << x / 10;
  out << "0123456789"[x % 10];
  return out;
}

std::istream& operator >>(std::istream&in, __int128 &x) {
  char c;
  while(c = in.get(), c != '-' && !isdigit(c));
  if(c == '-') {x = '0' - (c = in.get()); while(isdigit(c = getchar()))x = x * 10 + '0' - c;}
  else {x = c - '0'; while(isdigit(c = in.get()))x = x * 10 - '0' + c;};
  return in;
}

转载于:https://www.cnblogs.com/Forgenvueory/p/7725116.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值