2

I need to enter more than 10000 integers, smaller than max long long directly into console. The console accepts something more than 9000 of them using getline(cin,string). Inputting them one by one slows my program dramatically. Is there anyway that I can override the console's getline maximum input?

[Edited to include the OP's comment:]

#include <iostream>
using namespace std;
int main()
{
   long long n=0,i=0,a,b;
   cin>>n;
   for(i=0;i<n;i++) { cin>>a>>b; cout<<a+b<<endl; }
   return 0;
}

This code gives a "Time Limit Exceeded" error on the task when more than 10000 integers are inputted.

EDIT: After rewriting the code with help from one answer:

#include <iostream>

static inline int error(int n) { std::cerr << "Input error!\n"; return n; }

int main()
{
    long long a,b,n;  // number of colours and vertices

    if (!(std::cin>> n)) { return error(1); }

    for (int i = 0; i != n; ++i)
    {
        if (!(std::cin >> a>>b)) { return error(1); }
        std::cout << a+b << "\n";
    }
}

Now it gives me a Runtime Error(NZEC) on the test case with 10000+ integers

EDIT 2: I found something that would help me but it is only in C# : How to read very long input from console in C#? Couldn't find an equivalent in C++

Community
  • 1
  • 1
lunatic3331
  • 29
  • 1
  • 3
  • 6
    What's wrong with the direct `while (std::cin >> n) { /* store n */ }` loop? What do you mean by "dramatically slow"? How long does it take? Post some code that exhibits the slowness. – Kerrek SB May 06 '12 at 10:29
  • 2
    Your code violates the fundamental law of input reading: You fail to check the return value of the input operation. All other musings about the code are basically moot, as any number of things can go wrong and you don't even bother to check for them. See [this answer](http://stackoverflow.com/a/10467051/596781) for how to read input. – Kerrek SB May 06 '12 at 10:43

2 Answers2

7

By default iostreams are synchronized with C stdio functions and that makes them too slow for algorithmic contests. Disable synchronization at the beginning of your program:

std::ios::sync_with_stdio(false);
Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79
-1

You can take input from file. All you have to do is to redirect the stdin like this

if (!freopen("filename.txt", "r", stdin)) { 
    cout << "Could not open file";
    return 1;
}
long long n=0,i=0,a,b;
cin>>n;
for(i=0;i<n;i++) { cin>>a>>b; cout<<a+b<<endl; }
return 0;
Dewsworld
  • 13,367
  • 23
  • 68
  • 104
  • The question is explicitly about reading console input, what would redirecting stdin to a file achieve in that case, you wouldn't even read anything from the console at all. Also, if you want to read from a file, use fstream, don't redirect stdin... – KillianDS May 06 '12 at 12:03