从文件中获取字符串并将其拆分为

时间:2016-12-07 04:36:31

标签: c++

我正试图找到从文件中获取数字的最快方法。可能有负数。我的前妻。输入:

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

我正在使用:

getline(cin, line);

istringstream linestream(line);
linestream >> var;

结果没问题,但我的程序在上次测试时出现运行时错误,可能是分钟。 10万个号码。我的问题是,是否有更快的方法来获取字符串并将其拆分为数字而不是我的解决方案?时间是最重要的。

3 个答案:

答案 0 :(得分:1)

如果您的输入中只有数字,则可以执行以下操作:

std::vector<int> numbers;

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

要停止来自cin的输入,您需要发送EOF(文件结束)信号,该信号为 Ctrl + D 或< kbd> Ctrl + Z 取决于您的操作系统。

当到达文件末尾时,文件的输入将自动停止。

答案 1 :(得分:0)

请参阅c++ stringstream is too slow, how to speed up?

对于运行时错误,您没有发布可编译的代码,而且您的错误是您未发布的内容。

答案 2 :(得分:-1)

最好是制作一个逐行读取文件的函数,并将每个行元素放在一个数组中(如果你只打印它只是打印它不存储在数组中)。我使用的是c函数而不是c ++流,因为对于大数据,它们更快。当用于大数据时,函数应该使用比fscanf更快的fgetc。如果在你的系统中fgetc_unlocked工作正常,你应该将其替换为fgetc

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

假设输入如上所述并存储在input.txt中。只需在你的目录中创建input.txt并在同一个目录中运行以下代码。您可以稍后更改数字的使用方式

#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;
}
相关问题