0

I'm trying to find the fastest way for getting numbers from file. There can be negative numbers. My e.x. input:

5 3
-5 -6 2 -1 4
1 2 3 4
4 3 2 1

I'm using:

getline(cin, line);

istringstream linestream(line);
linestream >> var;

The result is okay but my program has run time error with last test, maybe min. 100 000 numbers. My question is, is there a faster way to get string and split it to numbers than my solution? The time is the most important.

Khalos
  • 39
  • 1
  • 4

3 Answers3

1

If there's only numbers in your input, you could do:

std::vector<int> numbers;

int i;
while(cin >> i) {
  numbers.push_back(i);
}

To stop the input from cin you'll need to send the EOF (End Of File) signal, which is either Ctrl+D or Ctrl+Z depending on your OS.

The input from a file will automatically stop when the end of the file is reached.

Jack Deeth
  • 3,062
  • 3
  • 24
  • 39
0

See c++ stringstream is too slow, how to speed up?

For your runtime error, you didn't post compilable code, and your error is in what you didn't post.

Community
  • 1
  • 1
KC Wong
  • 2,410
  • 1
  • 18
  • 26
-1

The best is make a function that reads a file line by line and puts each line elements in an array( if you are just printing just print it dont store in an array).I am using c function instead of c++ streams because for large data they are faster.The function should use fgetc which is faster than fscanf when used for large data.If in your system fgetc_unlocked works fine then you should replace that to fgetc

-5 -6 2 -1 4
1 2 3 4

Assume the input is like above and is stored in input.txt. Just make the input.txt in your dir and run the following code in the same dir. You can make changes later how you want to use the numbers

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

#define GC fgetc // replace with fgetc_unlocked if it works in your system(Linux)

//This function takes a line of f and put all integers into A
//and len is number of elements filled
void getNumsFromLine( FILE* f, int *A, int& len){
    register char ch=GC(f);
    register int n=0;
    register bool neg = false;
    len=0;

    while( ch!='\n' ){
        while( ch !='-' && (ch>'9' || ch<'0') ) ch=GC(f);
        if( ch=='-') {
            neg = true;
            ch = GC(f);
        }
        while( ch>='0' && ch<='9' ){
            n = (n<<3)+(n<<1)+ch-'0';
            ch = GC(f);
        }
        if(neg) {
            n=-n;
            neg=false;
        }
        A[len++]=n;
        n=0;
    }
}

int main(){

    FILE* f=fopen("input.txt", "r");
    int A[10][2],len;
    for( int i=0; i<2; i++ ){
        getNumsFromLine( f, A[i], len );
        for( int j=0; j<len; j++ ) cout << A[i][j] <<" ";
        cout << endl;
    }
    fclose(f);
    return 0;
}
Ankit Vallecha
  • 708
  • 7
  • 17