如何在循环中使用scanf?是否有一种很好的方法来循环字符串sscanf?假设我有一条看起来像这样的字符串:char line[] = "100 185 400 11 1000";我想打印这笔钱。我真正想写的是:int n, sum = 0;while (1 == sscanf(line, " %d", &n)) {
sum += n;
line += <number of bytes consumed by sscanf>}但是没有干净的方法可以把这些信息从sscanf..如果它返回所消耗的字节数,这将是有用的。在这种情况下,你可以用strtok,但是如果能写出一些类似于你能做的事情,那就太好了。stdin:int n, sum = 0;while (1 == scanf(" %d", &n)) {
sum += n;
// stdin is transparently advanced by scanf call}有什么简单的解决办法我忘了吗?
1 回答
桃花长相依
TA贡献1860条经验 获得超8个赞
%n
sscanf()
#include <stdio.h>int main(void){ char line[] = "100 185 400 11 1000"; char *data = line; int offset; int n; int sum = 0; while (sscanf(data, " %d%n", &n, &offset) == 1) { sum += n; data += offset; printf("read: %5d; sum = %5d; offset = %5d\n", n, sum, offset); } printf("sum = %d\n", sum); return 0;}
- 1 回答
- 0 关注
- 503 浏览
添加回答
举报
0/150
提交
取消