2017-03-12 118 views
-1

這裏是實驗目的: 編寫一個C++程序,用於檢索存儲在數據文件中的所有數字。隨着每個號碼的檢索,它會顯示在屏幕上。文件到達後,數字應按數字順序排序,然後顯示結果。從文本文件中讀取數字,然後顯示,然後排序(C++)

這裏是我的代碼:

int main(){ 
    fstream infile; 
    int numbers[25], size = 0, i = 0; 

    infile.open("lab1.txt"); 
    if (infile.fail()) 
    { 
     cout << "Error Opening File" << endl; 
    } 
    while (!infile.eof()) 
    { 
     infile >> numbers[i]; 
     cout << numbers[i] << endl; 
     i++; 
    } 


    size = i; 
    cout << size << " number of values in file" << endl; 

    for (int i = 0; i < size; ++i) { 
     for (int j = 0; j < size - i - 1; ++j) { 
      if (numbers[j] > numbers[j + 1]) 
      { 
       int temp = numbers[j]; 
       numbers[j] = numbers[j + 1]; 
       numbers[j + 1] = temp; 
      } 
     } 
    } 

    infile.close(); 

    return 0; 

} 

它使產生無限循環。有誰知道爲什麼?我很感謝任何幫助,謝謝

+0

聽過[性病::排序(http://en.cppreference.com/w/cpp/algorithm/sort)? –

+0

@JesperJuhl我們還沒有被教過,在課堂上,我的教授希望我們現在使用實際的循環和邏輯進行排序:\謝謝您 –

+0

如果文件無法打開,您只需打印一條消息並保留去。 – Shibli

回答

0

從聲明中刪除i變量。只使用size變量。

int main(){ 
    fstream infile; 
    int numbers[25], size = 0; 

    infile.open("lab1.txt"); 
    if (infile.fail()) 
    { 
     cout << "Error Opening File" << endl; 
    } 
    while (!infile.eof()) 
    { 
     infile >> numbers[size]; 
     cout << numbers[size] << endl; 
     size++; 
    } 

    cout << size << " number of values in file" << endl; 

    for (int i = 0; i < size - 1; ++i) { 
     for (int j = i+1; j < size; ++j) { 
      if (numbers[i] > numbers[j]) 
      { 
       //..... 
0

嘗試

char x; 
while (infile.get(x)){ 
    //add numbers to array 
} 
+0

你能擴展這個答案嗎? – GraphicsMuncher

相關問題