fscanf 获取双引号和数字之间的字符串
fscanf get string between double quotes and number
fscanf 从来没有进入我的脑海...
我正在扫描 /proc/partinfo 并且需要从名称中获取分区号。
换句话说:
在一行中:
part22: 02200000 01000000 "kernel"
我需要获取“内核”(不带引号)和 22
到目前为止我做了:
fscanf(fp,"%*5c%d%*c %*s %*s %s",&pnum,pname)
这给了我数字 22 和包含引号的“内核”。
如何不将它们包含在扫描线中?
我也不明白为什么 %*5c 有效,但应该是 %*4c 来跳过“部分”这个词。
char x[100] = {0}; // init not needed if you're careful enough with the return values
fscanf(fp, " \"%[^\"]\"", x); // matches quotemark, then non-quotemark chars, then the closing quotemark
// even better use e.g. %99[^\"] (i.e. bufsize-1) to prevent accidental buffer overrun
printf("->%s<-\n", x);
-->
->kernel<-
如果您的那部分代码处于循环中,或者遵循您未显示的其他类似逻辑,则可能是您未读取之前的换行符,并且 %5*c
正在吃掉 \n p a r t
。 part
之前也可能有一个真实的字符,可能是一个不可见的字符;我没有任何系统 /proc/partinfo
可以检查。
scanf
族函数被称为穷人的解析器,因为它们不是很强大,但它们可以扫描.
给你:
- 最多跳过一位数
- 读一个数
- 跳过双引号之前的任何内容
- 跳过双引号
- 读到下一个双引号
- 跳过双引号
使用 []
转换,你可以写成:
int cr = sscanf(input, "%*[^0-9]%d%*[^\"]\"%[^\"]\"", &pnum, pname);
它对额外的初始空格很稳健,或者如果您循环读取到上一行的终止 \n
。
注意:我使用 cr = ...
因为你应该 总是 控制输入函数的 return 值...
fscanf 从来没有进入我的脑海...
我正在扫描 /proc/partinfo 并且需要从名称中获取分区号。 换句话说:
在一行中:
part22: 02200000 01000000 "kernel"
我需要获取“内核”(不带引号)和 22
到目前为止我做了:
fscanf(fp,"%*5c%d%*c %*s %*s %s",&pnum,pname)
这给了我数字 22 和包含引号的“内核”。 如何不将它们包含在扫描线中?
我也不明白为什么 %*5c 有效,但应该是 %*4c 来跳过“部分”这个词。
char x[100] = {0}; // init not needed if you're careful enough with the return values
fscanf(fp, " \"%[^\"]\"", x); // matches quotemark, then non-quotemark chars, then the closing quotemark
// even better use e.g. %99[^\"] (i.e. bufsize-1) to prevent accidental buffer overrun
printf("->%s<-\n", x);
-->
->kernel<-
如果您的那部分代码处于循环中,或者遵循您未显示的其他类似逻辑,则可能是您未读取之前的换行符,并且 %5*c
正在吃掉 \n p a r t
。 part
之前也可能有一个真实的字符,可能是一个不可见的字符;我没有任何系统 /proc/partinfo
可以检查。
scanf
族函数被称为穷人的解析器,因为它们不是很强大,但它们可以扫描.
给你:
- 最多跳过一位数
- 读一个数
- 跳过双引号之前的任何内容
- 跳过双引号
- 读到下一个双引号
- 跳过双引号
使用 []
转换,你可以写成:
int cr = sscanf(input, "%*[^0-9]%d%*[^\"]\"%[^\"]\"", &pnum, pname);
它对额外的初始空格很稳健,或者如果您循环读取到上一行的终止 \n
。
注意:我使用 cr = ...
因为你应该 总是 控制输入函数的 return 值...