洛谷 P1957
题目链接:
在每一行,因为不确定第一个输入数据的类型,所以要用字符串输入。
值得注意的是,
int sprintf(char *buffer, const char *format [, argument] … );
,其第一个参数是char*类型,因此在使用
补充:const char* 转换成char*
有时我们需要把string类型的字符串转换成char*,但是string.c_str()等到的结果是const char*类型而不是char*类型,转换方法就是先把string转换成const char*,然后用sprintf把const char*转换成char*
示例:
string str; char* strchar; const char* strC = str.c_str(); sprintf(strchar,"%s",str.c_str());
AC代码:
#include <bits/stdc++.h> using namespace std; int main() { int n, x, y; cin >> n; while (n--) { char s[6], p[100]; char k; cin >> s; if (isalpha(s[0])) { k = s[0]; cin >> x >> y; } else { x = atoi(s); cin >> y; } if (k == 'a') sprintf(p, "%d+%d=%d", x, y, x + y); else if (k == 'b') sprintf(p, "%d-%d=%d", x, y, x - y); else sprintf(p, "%d*%d=%d", x, y, x * y); cout << p << "\n" << strlen(p) << "\n"; } return 0; }
x = atoi(s)可用sscanf(s, "%d", &x)替代。
本文作者:胖柚の工作室
本文链接:https://www.cnblogs.com/pangyou3s/p/17920235.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步