数字格式异常

NumberFormatException数字格式异常)编写一个程序,提示用户读取两个整数,然后显示他们的和。程序应该在输入不正确时提示用户再次输入数字。

输入格式:

i 9 (第1次输入) l 8 (第2次输入) 5 6 (第3次输入)

输出格式:

Incorrect input and re-enter two integers: (第1次输出提示) Incorrect input and re-enter two integers: (第2次输出提示) Sum is 11 (输出结果)

输入样例:

i 9
l 8
5 6

输出样例:

Incorrect input and re-enter two integers:
Incorrect input and re-enter two integers:
Sum is 11

代码如下:
#include <iostream>
#include<string>
//#include<cstdio>
#include<algorithm>
using namespace std;
int f;
int s2i(string &a)
{
	for(int i=0;i<a.size();i++)
	{
	if(a[i]<'0'||a[i]>'9'){
        f=0;
	}
	}
	if(f==1) return stoi(a);
    return -1;
}
int main ()
{
    string a,b;
    while(1)
    {
        cin>>a>>b;
        f=1;//如果将f=1;放进s2i函数第一句会出错,why
        int m=s2i(a);
        int n=s2i(b);
        if(f==0)
        {
            cout<<"Incorrect input and re-enter two integers:"<<endl;
            continue;
        }
        else
        {
            cout<<"Sum is "<<m+n<<endl;
            break;
        }
    }


}

  

转载于:https://www.cnblogs.com/cstdio1/p/11086497.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值