为什么 sscanf 不处理或忽略 C++ 中的空格?
Why sscanf is not handling or ignoring spaces in c++?
我要在 sscanf
中添加以下行,但它不接受空格
char store_string[25],store_string1[10];
std::tm t={};
int store_integer,store_integer1,store_integer2;
int total_read;
char* buff1 = "Demo to dispay (Appname,App usage) with date (03/11/2005) with test id (87773) data added (0) total ((null))";
char* buff2 = "Demo to dispay %s with date (%d/%d/%d) with test id (%d) data added (%d) total ((%d))";
total_read = sscanf(buff1, buff2 , store_string, &t.tm_mon,
&t.tm_mday,
&t.tm_year,
&store_integer,&store_integer1,&store_integer2);
输出:
如果 buff1
有显示 (Appname,Appusage)
它工作正常
但是如果 buff1
有显示 (Appname,App usage)
它会失败
Why sscanf is not handling or ignoring spaces in c++?
sscanf
还应该如何分隔 words/tokens?
来自其文档:
["%s"] matches a sequence of non-whitespace characters (a string)
我认为您根本无法使用 sscanf
或单行代码来处理此问题。
你可以用 std::string::find_first_of and std::string::substr
来做到这一点
编辑:
如果您习惯使用正则表达式,std::regex_match 可能是最灵活和可读性最强的方式。
我要在 sscanf
中添加以下行,但它不接受空格
char store_string[25],store_string1[10];
std::tm t={};
int store_integer,store_integer1,store_integer2;
int total_read;
char* buff1 = "Demo to dispay (Appname,App usage) with date (03/11/2005) with test id (87773) data added (0) total ((null))";
char* buff2 = "Demo to dispay %s with date (%d/%d/%d) with test id (%d) data added (%d) total ((%d))";
total_read = sscanf(buff1, buff2 , store_string, &t.tm_mon,
&t.tm_mday,
&t.tm_year,
&store_integer,&store_integer1,&store_integer2);
输出:
如果 buff1
有显示 (Appname,Appusage)
它工作正常
但是如果 buff1
有显示 (Appname,App usage)
它会失败
Why sscanf is not handling or ignoring spaces in c++?
sscanf
还应该如何分隔 words/tokens?
来自其文档:
["%s"] matches a sequence of non-whitespace characters (a string)
我认为您根本无法使用 sscanf
或单行代码来处理此问题。
你可以用 std::string::find_first_of and std::string::substr
编辑:
如果您习惯使用正则表达式,std::regex_match 可能是最灵活和可读性最强的方式。