【发布时间】:2015-07-27 20:41:48
【问题描述】:
我正在编写一个基本程序,它将从文本文件中读取整数列表并将文件中的最小整数和最大整数输出到屏幕。 我确保文本文件与源代码文件在同一个文件夹中,并且文件的名称与我在代码中的名称相同。无论如何,程序都无法打开文件。我该如何解决这个问题?
这是我的程序:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream inStream;
inStream.open("infile.txt");
if (inStream.fail())
{
cout<<"Input file opening failed.\n";
system("pause");
exit(1);
}
int arr[100], i = 0;
while(!inStream.eof())
{
inStream>>arr[i++];
}
int min = arr[0];
for (int index = 1; index <= i; index++)
{
if (arr[index] < min)
{
min = arr[index];
}
}
int max = arr[0];
for (int index = 1; index <= i; index++)
{
if (arr[index] > max)
{
max = arr[index];
}
}
cout<<"The smallest number is "<<min<<endl;
cout<<"The largest number is "<<max<<endl;
inStream.close();
system("pause");
return 0;
}
【问题讨论】:
-
请注意,您的程序还存在其他严重问题:带有
!eof前置条件的循环。它通常会导致您的程序“读取”比文件中实际存在的值更多的值(一个)。不要使用!eof作为前提条件。最重要的是,您的循环迭代直到index <= i(而不是index < i),这也将尝试访问数组中不存在的数据。 -
与其使用数组,不如保留两个变量:最小和最大。如果读取的整数较小,则变为最小;如果整数大于最大的,它就变成最大的。无需存储所有值。
-
@ThomasMatthews 我不明白如果不将文件中的所有数字存储在一个数组中以便使用它们并输出结果,如何做到这一点。你能解释更多吗?
-
将
smallest设置为MAX_INT。将largest设置为MIN_INT。循环:从文件中读取值。if (value < smallest) smallest = value; if (value > largest) largest = value;。结束循环。MAX_INT和MIN_INT在limits.h中定义,可以命名为INT_MAX和INT_MIN。 -
@ThomasMatthews 什么是limits.h?我认为这可能超出了我在课堂上所学的内容或我教科书中的任何内容。有没有更简单的方法来设置最大值和最小值?