c++如何保证输入始终是数字而不是字符?

// my_structur.cpp -- 创建结构体数组,循环输入结构体元素。
// 1 创建结构体;
// 2 创建结构体数组;
// 3 循环输入结构体元素时保证始终输入字符串或数字;
//  3.1 while (1) {}
#include <iostream>
#include <cstring>
struct inflatable // structure declaration
{
    char name[20];
    float volume;
    double price;
};

int main()
{
    using namespace std;
    // my structure array test
    inflatable guest_array[3];
    for (int i = 0; i < 3; i++)
    {
        cout << "Please input name: " << endl;
        // cin.getline(guest_array[i].name, 20);
        // cin>> noskipws >> guest_array[i].name;

        cin.get(guest_array[i].name, 20);

        cout << "Please input volume: " << endl;
        while (!(cin >> guest_array[i].volume))
        {
            cout << "无效输入! 请重新输入数字:" << endl;
            cin.clear();
            cin.ignore(1024, '\n');
        }

        // while (!scanf("%d", &guest_array[i].volume) || guest_array[i].volume < 0)
        // {
        //     printf("无效输入!请重新输入:\n");
        //     scanf("%*[^\n]");
        //     scanf("%*c");
        // }

        cin.get();

        cout << "Please input price: " << endl;
        cin >> guest_array[i].price;
        cin.get();

        cout << "name" << i << ": " << guest_array[i].name << endl;
        cout << "volume: " << guest_array[i].volume << endl;
        cout << "price: " << guest_array[i].price << endl;
    }

    return 0;
}

 

上述代码中,需要联合使用cin.clear()和cin.ignore(1024, '\n');

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值