這裏是實驗目的: 編寫一個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;
}
它使產生無限循環。有誰知道爲什麼?我很感謝任何幫助,謝謝
聽過[性病::排序(http://en.cppreference.com/w/cpp/algorithm/sort)? –
@JesperJuhl我們還沒有被教過,在課堂上,我的教授希望我們現在使用實際的循環和邏輯進行排序:\謝謝您 –
如果文件無法打開,您只需打印一條消息並保留去。 – Shibli