题的目标很简单,就是求两个正整数A和B的和,其中A和B都在区间[1,1000]。稍微有点麻烦的是,输入并不保证是两个正整数。
输入格式:
输入在一行给出A和B,其间以空格分开。问题是A和B不一定是满足要求的正整数,有时候可能是超出范围的数字、负数、带小数点的实数、甚至是一堆乱码。
注意:我们把输入中出现的第1个空格认为是A和B的分隔。题目保证至少存在一个空格,并且B不是一个空字符串。
输出格式:
如果输入的确是两个正整数,则按格式A + B = 和输出。如果某个输入不合要求,则在相应位置输出?,显然此时和也是?。
输入样例1:
123 456
输出样例1:
123 + 456 = 579
输入样例2:
- 18
输出样例2:
? + 18 = ?
输入样例3:
-100 blabla bla…33
输出样例3:
? + ? = ?
代码
#include <bits/stdc++.h>
using namespace std;
int transf(string s)
{
if(s[0]=='-') return -1;
int k=s[0]-'0';
if(k<0||k>9) return -1;
for(int i=1;i<s.length();i++)
{
k=s[i]-'0';
if(k<0||k>9) return -1;
}
stringstream ss;
ss<<s;
int x;
ss>>x;
if(x>1000||x<1) return -1;
return x;
}
int main()
{
string str,str1,str2;
getline(cin,str);
int pos=str.find(' ');
str1=str.substr(0,pos);
str2=str.substr(pos+1);
//cout<<str1<<"-"<<str2;
int a=transf(str1);
int b=transf(str2);
if(a==-1) cout<<'?';
else cout<<a;
cout<<" + ";
if(b==-1) cout<<'?';
else cout<<b;
cout<<" = ";
if(a==-1||b==-1) cout<<'?';
else cout<<a+b;
return 0;
}
总结
- 关键点1:如何拆分两个字符串。由于题目“我们把输入中出现的第1个空格认为是A和B的分隔。题目保证至少存在一个空格,并且B不是一个空字符串。”,而cin识别字符串到空格截止,从空格后继续识别,导致可能漏掉空格。eg.12 34应该是12 + ? = ?而不是12 + 34 = 46
故先作为一个字符串读入,然后根据第一个空格的位置进行拆分。 - 关键点2:string向int的转换
- 输出时本来想用a==-1?’?’:a的,编译报错。不能把字符给int变量。