PTA positive integer A+B (regular expression)

The goal of the question is very simple, which is to find the sum of two positive integers A, Bwhere Aboth Bsums are in the interval [1,1000]. Slightly troublesome, the input is not guaranteed to be two positive integers.

Input format:

AInput gives and on one line B, separated by spaces. The problem is Athat Bthe sum is not necessarily a positive integer that meets the requirements. Sometimes it may be a number that is out of range, a negative number, a real number with a decimal point, or even a bunch of garbled characters.

Note: We regard the first space that appears in the input as the separation of Aand B. The title guarantees at least one space and Bnot an empty string.

Output format:

If the input is indeed two positive integers, the A + B = 和output is formatted. If an input does not meet the requirements, it is output at the corresponding position ?, obviously at this time and also ?.

Example 1:

123 456

Output sample 1:

123 + 456 = 579

Input sample 2:

22. 18

Output sample 2:

? + 18 = ?

Input sample 3:

-100 blabla bla...33

Output sample 3:

? + ? = ?

important point:

  • A and B are positive integers in the range of [1,1000]
  • A can be an empty string

AC code

#include<bits/stdc++.h> 
using namespace std;
int f,idx;
string s,a,b;
signed main()
{
	getline(cin,s);
	idx=s.find(" ");
	a=s.substr(0,idx);
	b=s.substr(idx+1);
//	正则表达式[1-9][0-9]*表示第一个字符为1-9的数字(可以排除只有0或者前缀有0的情况),后面的字符可以有0个或多个0-9的数字 
	if(regex_match(a,regex("[1-9][0-9]*"))&&stoi(a)<=1000) cout<<stoi(a),f++; 
	else cout<<"?";
	cout<<" + ";
	if(regex_match(b,regex("[1-9][0-9]*"))&&stoi(b)<=1000) cout<<stoi(b),f++;
	else cout<<"?";
	cout<<" = "; 
	if(f==2) cout<<stoi(a)+stoi(b);
	else cout<<"?";
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_61725823/article/details/130209834