C/C++程序中经常在输入过程中通过判断是否输入回车符来判断程序是否结束。针对此应用,对存在的若干问题进行说明。
1.示例程序1——C语言
1.1 程序源码
输入一系列未知个数的数字,然后输出max ,min和average。
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
#pragma warning(disable:4996)
int main()
{
int temp,n;
int max, min, sum;
scanf("%d", &temp);
max = min = sum = temp; //Init
n = 1;
while (scanf("%d", &temp)==1)
{
sum += temp;
if (max <= temp) max = temp;
if (min >= temp) min = temp;
n++;
}
printf("%d %d %.3lf\n",max,min,(double)(sum/n));
system("pause");
return 0;
}
程序停留在输入阶段,不能执行结果输出语句
1.2 问题分析
(1)scanf()的返回值是输入数据的个数,例如在scanf(“%d”,&temp)中正常情况下返回值为1
(2) scanf在检测输入时候由于scanf(“%d”,&temp)规定了整数输入,所以scanf对空格,回车和制表符号等并不检测。在键盘上输入回车之后,程序并未检测到程序输入结束,依旧停留在while(scanf(“%d”,&temp))这一行中。
1.3 问题解决
(1)方法一:
在程序窗口cmd中输入Ctrl+D(起回车作用),程序会向下继续运行
修改代码,用getchar()判断程序是否结束。将原代码中while语句修改为
while((scanf("%d", &temp) == 1)&& (getchar() != '\n'))
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
#pragma warning(disable:4996)
int main()
{
int temp,n;
int max, min, sum;
scanf("%d", &temp);
max = min = sum = temp; //Init
n = 1;
while((scanf("%d", &temp) == 1) && (getchar() != '\n'))
{
sum += temp;
if (max <= temp) max = temp;
if (min >= temp) min = temp;
n++;
}
printf("%d %d %.3lf\n",max,min,(double)(sum/n));
system("pause");
return 0;
}
(3)方法三(不推荐):
人为输入错误信息,如字母或浮点数等
2. 示例程序2——C++语言
2.1 程序源码
上述示例用C++可以表示为:
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
#pragma warning(disable:4996)
int main()
{
int temp, n;
int max, min, sum;
cin>>temp;
max = min = sum = temp; //Init
n = 1;
while (cin >> temp)
{
sum += temp;
if (max <= temp) max = temp;
if (min >= temp) min = temp;
n++;
if (getchar() == '\n') break;
}
cout <<max<<' ' <<min<<' '<<(double)sum/n<< endl;
system("pause");
return 0;
}