2016-12-07 53 views
0

我正试图从文件中获取数字的最快方法。可以有负数。我的前夫。输入:从文件中获取字符串并将其拆分

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个号码。我的问题是,有没有更快的方式来获得字符串,并将其拆分为数字比我的解决方案?时间是最重要的。

+0

你是什么意思的“分裂为数字”?你的意思是将它们转换为字符串? – CroCo

回答

1

如果只有在你输入号码,你可以这样做:

std::vector<int> numbers; 

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

cin停止输入你需要发送的EOF(文件的结束)信号,这要么是按Ctrl + DCtrl + Z取决于您的操作系统。

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

0

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

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