7-5 正整数A+B (15分)

题的目标很简单,就是求两个正整数A和B的和,其中A和B都在区间[1,1000]。稍微有点麻烦的是,输入并不保证是两个正整数。
输入格式:

输入在一行给出A和B,其间以空格分开。问题是A和B不一定是满足要求的正整数,有时候可能是超出范围的数字、负数、带小数点的实数、甚至是一堆乱码。

注意:我们把输入中出现的第1个空格认为是A和B的分隔。题目保证至少存在一个空格,并且B不是一个空字符串。

输出格式:

如果输入的确是两个正整数,则按格式A + B = 和输出。如果某个输入不合要求,则在相应位置输出?,显然此时和也是?。

输入样例1:

123 456

输出样例1:

123 + 456 = 579

输入样例2:

22. 18

输出样例2:

? + 18 = ?

输入样例3:

-100 blabla bla...33

输出样例3:

? + ? = ?

很简单,一看就懂

#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
using namespace std;

int main() {
    
    
    string s;
    getline(cin,s);
    int flagA=1,flagB=1;
    int i;
    int j;
    int sumA=0,sumB=0;
    for(i=0;s[i]!=' ';i++){
    
    
    	if(s[i]>='0'&&s[i]<='9'){
    
    
    		sumA=10*sumA+(s[i]-'0');
    		
		}
    	else{
    
    
    		flagA=0;
		}
	}
	for(j=i+1;s[j]!='\0';j++){
    
    
		if(s[j]>='0'&&s[j]<='9'){
    
    
			sumB=10*sumB+(s[j]-'0');
			
		}
		else{
    
    
			flagB=0;
		}
	}
	if(sumA<1||sumA>1000){
    
    
		flagA=0;
	}
	if(sumB<1||sumB>1000){
    
    
		flagB=0;
	}
	if(flagA){
    
    
		if(flagB){
    
    
			cout<<sumA<<" "<<"+"<<" "<<sumB<<" = "<<sumA+sumB;
		}
		else{
    
    
			cout<<sumA<<" + "<<"?"<<" = "<<"?"; 
		}
	}
	else{
    
    
			if(flagB){
    
    
			cout<<"?"<<" "<<"+"<<" "<<sumB<<" = "<<"?";
		}
		else{
    
    
			cout<<"?"<<" + "<<"?"<<" = "<<"?"; 
		}
	}
    
}

猜你喜欢

转载自blog.csdn.net/weixin_45962741/article/details/112808612