c++ - 如何使用 fscanf() 扫描宽度 = 2 的 UINT?
问题描述
我需要读取像“01”这样的数据,但跳过像“1”这样的数据。我试过fscanf(f, "%2lu ", &ulong)
了,但似乎 2 是最大长度,不是固定的。
是的,我知道我可以用 %c%c 之类的符号来做到这一点,但是阅读代码会更难。
我应该怎么办?
解决方案
使用"%n"
转换说明符
#include <stdio.h>
int main(void) {
long n;
int m1, m2;
if (sscanf(" 123\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error");
if (m2 - m1 != 2) puts("error with 123");
if (sscanf(" 12\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error");
if (m2 - m1 != 2) puts("error with 12");
if (sscanf(" 1\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error");
if (m2 - m1 != 2) puts("error with 1");
return 0;
}
更好的是:永远不要scanf()
用于用户输入。
推荐阅读
- java - 使用导航组件折叠工具栏
- android - 使用 UiDevice 滑动的 x,y 边界是多少
- android - 2个相似片段之间的共享元素转换
- javascript - 为什么 v-model 在 vue.extend 中使用时不起作用?
- python - scikit-image熵计算的边界条件是什么
- flutter - 如何使 ListView 水平滚动?
- aspnetboilerplate - 来自 Angular 的 API 调用无效 - remoteServiceBaseUrl 中的占位符
- python - python中的字符串格式化%s
- python - 使用python在postgresql中添加uuid列
- azure-language-understanding - 我们如何通过节点 js 代码中的 API 在 luis 中添加意图和话语