2016-12-07 93 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; 
} 
相關問題