c - sscanf忽略C中的空格
问题描述
char s[20] = "test1 16 test2";
char a[20]; char b[20];
sscanf(s, "%s%*d%s", a, b);
printf("'%s' '%s'", a, b); //'test1' 'test2'
sscanf 是否已预先编程为忽略空格?
我期待:
'test1 ' ' test2'.
解决方案
要在扫描的字符串中包含空格%n
,用于捕获扫描处理的字符数的说明符可能是更好的选择。"%s %n
将记录第一个单词和尾随空格处理的字符数。%*d%n
将扫描并丢弃整数并记录处理的字符总数到整数末尾。然后%s%n
将跳过空格并扫描最后一个单词并记录处理的字符总数。
用于strncpy
复制单词和空格。
#include <stdio.h>
#include <string.h>
#define SIZE 19
//so SIZE can be part of sscanf Format String
#define FS_(x) #x
#define FS(x) FS_(x)
int main ( void) {
char s[SIZE + 1] = "test1 16 test2";
char a[SIZE + 1]; char b[SIZE + 1];
int before = 0;
int after = 0;
int stop = 0;
if ( 2 == sscanf(s, "%"FS(SIZE)"s %n%*d%n%"FS(SIZE)"s%n", a, &before, &after, b, &stop)) {
if ( before <= SIZE) {
strncpy ( a, s, before);//copy before number of characters
a[before] = 0;//terminate
}
if ( stop - after <= SIZE) {
strncpy ( b, &s[after], stop - after);//from index after, copy stop-after characters
b[stop - after] = 0;//terminate
}
printf("'%s' '%s'\n", a, b);
}
return 0;
}
推荐阅读
- javascript - ExpressJS RESTapi 动态设置路由
- ruby - 如何将文件夹引用添加到 PBXGroup?
- bash - 尝试 grep 时出现错误“期望:生成 id exp4 未打开”
- excel - Excel VBA 应用程序总和
- c++ - 是什么导致我的“命名空间'Foam'中的'FatalError'没有命名类型”错误?
- ios - 仅从日期数组中删除时间 Swift
- javascript - 即使应用了我在网上可以找到的所有方法,我的页面也没有滚动
- java - 错误:(3, 31) java: com.sun.tools.javac.jvm 包不存在
- python - 使用 Range-Elasticsearch 过滤
- r - ShinyProxy Euler App 未运行 - 无法启动容器