c++学习笔记——读取数字的循环

该C++程序从用户处获取鱼的重量,允许非数字输入来终止循环。当遇到非数字输入时,程序会清除输入流的错误状态,删除错误行,并提示用户重新输入数字。程序最后计算平均重量。改进后的版本增加了错误处理和用户反馈。
摘要由CSDN通过智能技术生成
// cinfish.cpp -- non-numeric input terminates loop
#include <iostream>
const int Max = 5;
int main()
{
    using namespace std;
// get data
    double fish[Max];
    cout << "Please enter the weights of your fish.\n";
    cout << "You may enter up to " << Max
            << " fish <q to terminate>.\n";
    cout << "fish #1: ";
    int i = 0;
    while (i < Max && cin >> fish[i]) {
//abd运算符表达式的左侧为false,则c++将不会判断右侧的表达式
        //这里的表达式进行判定意味着cin输入放在数组中,如果i等于Max,则循环结束。
        if (++i < Max)
            cout << "fish #" << i+1 << ": ";
    }
// calculate average
    double total = 0.0;
    for (int j = 0; j < i; j++)
        total += fish[j];
// report results
    if (i == 0)
        cout << "No fish\n";
    else
        cout << total / i << " = average weight of "
            << i << " fish\n";
    cout << "Done.\n";
// code to keep VC execution window open if q is entered
//	if (!cin)  // input terminated by non-numeric response
//	{
//	    cin.clear();  // reset input
//	    cin.get();    // read q
//	}
//	cin.get();    // read end of line after last input
//	cin.get();    // wait for user to press <Enter>
    return 0; 
}
Please enter the weights of your fish.
You may enter up to 5 fish <q to terminate>.
fish #1: 8
fish #2: 5
fish #3: 4
fish #4: 5
fish #5: q
5.5 = average weight of 4 fish
Done.

下面对上面的程序进行改进:

(1)重置cin以接受新的输入

(2)删除错误输入

(3)提示用户再输入

#include <iostream>
const int Max = 5;
int main()
{
    using namespace std;
    int golf[Max];
    cout << "Please enter your golf scores.\n";
    cout << "You must enter " << Max << " round.\n";
    int i;
    for (i = 0; i < Max; i++)
    {
        cout << "round #" << i+1 << " : ";
        while ( !(cin >> golf[i] )){
                cin.clear();
                //使用clear()方法重置cin,如果省略这条语句,程序将拒绝继读取输入。
                //cin.clear();  clear()函数不是清除输入,而是清除错误状态。 
                //标准库的IO类如果出错,会为自身设置错误状态,这时是不能继续输入/输出的。 所以要先clear错误状态。
                while (cin.get() != '\n')
                //使用cin.get()来读取行尾之前的所有输入,从而删除这一行中的错误输入。这种是方法时一次性删除整行
                //这一句不停从输入缓冲区中读取已经输入的字符,直到读走'\n'。这其实就是要消耗掉输入缓冲区中刚才错误输入的剩余内容。
                //具体原理见课本第17章
                    continue;
                cout << "Please enter a number: ";

        }
    }
    double total = 0.0;
    for (i = 0; i < Max; i++)
        total += golf[i];
    cout << total / Max << " = average score "
        << Max << " round\n";
    return 0;
}
You must enter 5 round.
round #1 : 8
round #2 : d
Please enter a number: 5
round #3 : 6
round #4 : 8
round #5 : 9
7.2 = average score 5 round

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值