Qualified's blog

By Qualified, history, 3 years ago, In English

I very much like $$$cin » $$$ but want to have this fast reading integers function. How to do it? For example, I want to input multiple integers in this $$$cin » a » b » c;$$$ but the reading of integers is using the comment above.

I tried this but it didn't work.

istream & operator >> (istream& os, int x) {
	bool minus = false;
	int result = 0;
	char ch;
	ch = getchar();
	while (true) {
		if (ch == '-') break;
		if (ch >= '0' && ch <= '9') break;
		ch = getchar();
	}
	if (ch == '-') minus = true; else result = ch-'0';
	while (true) {
		ch = getchar();
		if (ch < '0' || ch > '9') break;
		result = result*10 + (ch - '0');
	}
	if (minus)
		os >> -result;
	else
		os >> result;
	return os;
}

But I got this error

 error: ambiguous overload for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'int')
  124 |   os >> result;
      |   ~~ ^~ ~~~~~~
      |   |     |
      |   |     int
  • Vote: I like it
  • -5
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Qualified (previous revision, new revision, compare).

»
3 years ago, # |
  Vote: I like it +14 Vote: I do not like it

You cannot overload a previously declared function with the same arguments. The only way to create your own class.

The implementation looks like this. Not pretty, but it works.


#include <bits/stdc++.h> using namespace std; class custom_stream { public: template<typename T> friend custom_stream & operator >> ( custom_stream &is, T &x ){ std::cin >> x; return is; } friend custom_stream & operator >> ( custom_stream &is, int &x ){ bool minus = false; int result = 0; char ch; ch = getchar(); while( true ) { if ( ch == '-' ) break; if ( ch >= '0' && ch <= '9' ) break; ch = getchar(); } if( ch == '-' ) minus = true; else result = ch-'0'; while( true ) { ch = getchar(); if ( ch < '0' || ch > '9' ) break; result = result*10 + (ch - '0'); } if( minus ) x = -result; else x = result; return is; } }; #define cin in custom_stream in; int main() { int n; cin >> n; cout << n << endl; }