Abnormal digital format

NumberFormatException digital format abnormal) Write a program that prompts the user to read two integers, and then display them. Program should prompt the user to enter the number again when input is incorrect.

Input formats:

i 9 (1st input) l 8 (2nd input) 56 (3rd input)

Output formats:

Incorrect input and re-enter two integers: (1st output tips) Incorrect input and re-enter two integers: (2nd output tips) Sum is 11 (output)

Sample input:

i 9
l 8
5 6

Sample output:

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

code show as below:
#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;
        }
    }


}

  

Guess you like

Origin www.cnblogs.com/cstdio1/p/11086497.html