自测和数据一样,为什么爆0

P1957 口算练习题

⚡zhangjingcan⚡ @ 2020-12-19 11:13:05

#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void read(T &x){
    char c=getchar();x=0;bool f=0;
    while(!isdigit(c))f^=!(c^45),c=getchar();
    while(isdigit(c))x=(x<<1)+(x<<3)+(c^48),c=getchar();
    if(f)x=-x;
}
char s[101], ans[101];
int n, x, y;
char op;
int main(){
    read(n);
    for(int i = 1; i <= n; i++) {
        gets(s);
        if(s[0] >= 'a' && s[0] <= 'z') {
            sscanf(s, "%c%d%d", &op, &x, &y);
        }
        else if(s[0] >= '0' && s[0] <= '9'){
            sscanf(s, "%d%d", &x, &y);
        }
        memset(ans, 0, sizeof(ans));
        if(op == 'a') sprintf(ans, "%d+%d=%d", x, y, x + y);
        else if(op == 'b') sprintf(ans, "%d-%d=%d", x, y, x - y);
        else if(op == 'c') sprintf(ans, "%d*%d=%d", x, y, x * y);
        cout << ans << "\n" << strlen(ans) << "\n";
    }
    return 0;
}

显示 Too short on line 1.


by szkzyc @ 2020-12-19 11:16:06

关于gets,它SPFA


by 蒟蒻炒扇贝 @ 2020-12-19 11:17:18

小 心 "%c"

建议在输入字符后加个空格,像这样

sscanf(s, "%c %d%d", &op, &x, &y);

by 蒟蒻炒扇贝 @ 2020-12-19 11:17:43

而且gets要慎用,极不稳定


by ⚡zhangjingcan⚡ @ 2020-12-19 11:20:23

@扇贝sann 换成cin.getline也不行


by vandijk @ 2020-12-19 11:51:40

@⚡zhangjingcan⚡ "\n" 的问题?


by ⚡zhangjingcan⚡ @ 2020-12-19 11:58:03

@orz_MSQ 是把输出的"\n"换成endl吗


by vandijk @ 2020-12-20 12:52:53

@⚡zhangjingcan⚡ bjd


by ⚡zhangjingcan⚡ @ 2020-12-21 22:43:11

是gets的问题,在read(n); 后面加个getchar();就OK了,此贴完结


|