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

Getting string from file and split that

本文关键字:串并 拆分 字符串 字符 文件 获取      更新时间:2023-10-16

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

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

我正在使用:

getline(cin, line);
istringstream linestream(line);
linestream >> var;

结果还可以,但是我的程序在上次测试中有运行时间错误,也许是最小的。100 000个数字。我的问题是,是否有一种比我的解决方案更快地将字符串分为数字的方法?时间是最重要的。

如果输入中只有数字,则可以这样做:

std::vector<int> numbers;
int i;
while(cin >> i) {
  numbers.push_back(i);
}

要停止cin的输入/kbd> z 取决于您的操作系统。

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

请参阅C 弦乐太慢,如何加快速度?

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

最好的是制作一个函数,该函数逐行读取文件,并将每个行元素放入数组中(如果您只是在打印只是打印,则不要将其存储在数组中)。我am使用C函数代替C 流,因为对于大数据,它们应使用用于大数据时的FGETC,该功能应比FSCANF快。

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

假设输入如上所述,并存储在Input.txt中。只需在dir中制作input.txt,然后在同一dir中运行以下代码。您可以稍后进行更改,如何使用数字

#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;
}