【C++】学习笔记二十七——读取数字的循环

  假设要将一系列数字读入到数组中,并允许用户在数组填满之前结束输入。一种方法是利用cin:

int n;
cin >> n;

  如果用户输入一个单词而不是数字,将发生:

  • n的值保持不变;
  • 不匹配的输入将被保留在输入队列中;
  • cin对象中的一个错误标记被设置;
  • 对cin方法的调用将返回false。

      返回false意味着可以用非数字输入来结束读取数字的循环。非数字输入设置错误标记意味着必须重置该标记,程序才能继续读取输入。clear()重置输入错误标记,同时也重置文件尾(EOF)。输入错误和文件尾都会导致cin返回false。
      


程序6.13

#include<iostream>
const int Max = 5;
int main()
{
    using namespace std;
    double  fish[Max];
    cout << "Please enter the weights of your fish.\n";
    cout << "You may ennter up to " << Max
        << " fish <q to terminate>.\n";
    cout << "fish #1: ";
    int i = 0;
    while (i<Max && cin >> fish[i])
    {
        if (++i < Max)
            cout << "fish #" << i + 1 << ": ";
    }
    double total = 0.0;
    for (int j = 0; j < i; j++)
        total += fish[j];

    if (i == 0)
        cout << "No fish\n";
    else
        cout << total / i << " = average weight of "
        << i << " fish\n";
    cout << "Done.\n";
    system("pause");
    return 0;
}

这里写图片描述


  
程序6.14

#include<iostream>
const int Max = 5;
int main()
{
    using namespace std;
    //get data
    int golf[Max];
    cout << "Please enter your golf scores.\n";
    cout << "You must enter " << Max << " rounds.\n";
    int i;
    for (i = 0; i < Max; i++)
    {
        cout << "round #" << i + 1 << ": ";
        while (!(cin >> golf[i])) {
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Please enter a number: ";
        }
    }
    //calculate average
    double total = 0.0;
    for (i = 0; i < Max; i++)
        total += golf[i];
    //report results
    cout << total / Max << " = average score " << Max << " rounds\n";
    system("pause");
    return 0;
}

这里写图片描述
  
  在程序6.14中,关键部分如下:
  

        while (!(cin >> golf[i])) {
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Please enter a number: ";
        }

  如果用户输入88,则cin表达式将为true,因此将一个值放到数组中;而表达式!(cin>>golf[i])为false,因此内部循环结束。然而,如果用户输入must i?,则cin表达式将为false,因此不会将任何值放到数组中;而表达式!(cin>>golf[i])将为true,因此进入内部的while循环。该循环的第一条语句使用clear()来重置输入,如果省略这条语句,程序将拒绝读取输入;接下来,程序在while循环中使用cin.get()来读取行尾之前的所有输入,从而删除这一行中的错误输入。另一种方法是读取到下一个空白字符,这样将每次删除一个单词,而不是一次删除整行。最后程序告诉用户,应输入一个数字。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值