C++ Cin输入数字时 输入字母 Cin状态出错

在做某个小程序时有一个判断输入数字的需求

当时我是这么写的

	int num = -1;
	//input the total num of XXX 
	cout << "Please input the num of XXX :    ";
	cin >> num;
	while  (num <= 0)
	{
	
		cout << "\nPlease input the num of XXX:    ";
		cin >> num;
	}




情况就是while里面的cin不起作用了。Debug查看num的值一直是-1.地址也没变,cin也一直被触发。所以做的关于变量变化的猜测都推翻了。

那么情况就是cin本身出了问题。

首先参考老司机的方案,linux程序员常用的方法通过字符串输入变量然后转成int。这个方法还是成功解决了问题。

	string strNum;
	//input the total num of XXX
	cout << "Please input the num of XXX :    ";
	cin >> strNum;
	int num = atoi(strNum.c_str());
	while (num <= 0)
	{

		cout << "\nPlease input the num of Fingo parts :    ";
		cin >> strNum;
		num = atoi(strNum.c_str());
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值