这是实验室目标: 编写一个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 :(得分: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])
{
//.....
答案 1 :(得分:0)
尝试
char x;
while (infile.get(x)){
//add numbers to array
}