C++ - Which is faster : Taking n integers as input vs taking input as a string and splitting it into integer

Which method will work faster between these two -

#include<iostream>
using namespace std;
int main() {
    int n;
    cin >> n;
    int arr[n];
    for(int i = 0; i < n; i++)
        cin >> arr[i];
}

OR

#include<iostream>
#include <string>
#include <sstream>

int main() {
    int n;
    cin >> n;
    int arr[n];
    std::string s;
    cin << s;
    std::istringstream is( s );
    int i,j=0;
    while( is >> i ) {
         arr[j++] = i;
    }
}

I generally have read that I/O are slower. So will the 2nd method work faster than the 1st?

1 answer

  • answered 2018-07-11 10:08 A_Singh7

    Firstly, your second code you wrote has a lot of errors. It should be like this :

    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    
    int main() 
    {
    int n;
    cin >> n;
    int arr[n];
    std::string s;
    cin >> s;
    std::istringstream is( s );
    int i,j=0;
     while( is >> i ) 
     {
         arr[j++] = i;
     }
    return 0;
    }
    
    • Secondly, You should use std::vector, instead of int arr[n]. It is a good practice in C++.
    • Thirdly, Your question which you have asked cannot be determined be anyone of us. The size of the array shall be known at the compile time.