思路简析
- 初始拿到这道题的时候其实也没有太多思路,想着定义什么类型好(因为输入的对象是什么还不知道),于是干脆定为string型。
- 输入A的时候注意只要到第一个空格之前,所以用 getline(cin, A, ’ ');
- 判断一个字符是否为数字用isdigit
- stoi可以将字符型转为数字
- 利用上述函数可以很好的将题目做出
解法代码
#include<iostream>
#include<cstring>
#include<ctype.h>
using namespace std;
int main() {
string A, B;
getline(cin, A, ' ');
getline(cin, B);
bool shuA = true;
bool shuB = true;
for (int i = 0; i < A.length(); i++) {
if(!isdigit(A[i])) shuA = false;
}
for (int i = 0; i < B.length(); i++) {
if(!isdigit(B[i])) shuB = false;
}
if (shuA) {
if (stoi(A) > 1000 || stoi(A) < 1) shuA = false;
}
if (shuB) {
if (stoi(B) > 1000 || stoi(B) < 1) shuB = false;
}
if (shuA && shuB) {
cout << stoi(A) << " + " << stoi(B) << " = " << stoi(A) + stoi(B);
}else if (shuA) {
cout << stoi(A) << " + " << "?" << " = " << "?";
}else if (shuB) {
cout << "?" << " + " << stoi(B) << " = " << "?";
}else {
cout << "?" << " + " << "?" << " = " << "?";
}
return 0;
}
相关知识
一些输入的函数C++:cin、cin.getline()、getline()的用法_getline(cin,s)函数用法-优快云博客
判断字符或字符串是否为数字C++中使用isdigit()函数判断字符或字符串是否是数字_c++ isdigit-优快云博客
判断字符书否位数字判断一个字符是否为数字的两种方法(C/C++)_c语言判断是否为数字-优快云博客