且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解析一个简单的字符串

更新时间:2023-11-05 08:18:52

mathieu写道:
mathieu wrote:
你好,

我正在尝试解析一个字符串而我对结果感到惊讶(*)
使用时:
sscanf(s,%03u%c,& val,& f);
如果数字小于3找到数字,不应该报告那个吗?
Hello,

I am trying to parse a string and I am surprised by the result(*)
When using:
sscanf(s, "%03u%c", &val, &f);
If a number less than 3 digits is found, shouldn''t sscanf report
that ?



scanf转换说明符与printf'不同。 %03u

显然不会做你想象的那样。 0是多余的并且

3只表示要转换的*最大*字符数

(在跳过任何前导空格之后)为3。 br $> b $ b查看您的文档以获取详细信息。


Robert Gamble



scanf conversion specifiers are not the same as printf''s. The %03u
obviously doesn''t do what you think it does. The 0 is superfluous and
the 3 just indicates that the *maximum* number of characters to be read
(after skipping any leading whitespace) for that conversion is 3.
Check your documentation for details.

Robert Gamble


Oooops我错过了''最大值''。感谢您的信息。

我想我只是确保所有三个第一个字符都是

十进制。


Mathieu

Oooops I missed the ''maximum''. Thanks for the info.
I guess I simply make sure that all of the three first char are
decimal.

Mathieu


仅供参考。以下是最终解决方案:


void parse(const char * s)

{

unsigned int val;

char f;

if(!isdigit(s [0])

||!isdigit(s [1])

||!isdigit(s [2]))

{

printf(" error\\\
);

}

else

{

int k = sscanf(s,"%03u%c",& val,& f);

printf("%d%u%c\ n,k,val,f);

}

}

Just for ref. Here is the final solution:

void parse(const char *s)
{
unsigned int val;
char f;
if( !isdigit(s[0])
|| !isdigit(s[1])
|| !isdigit(s[2]))
{
printf( "error\n");
}
else
{
int k = sscanf(s, "%03u%c", &val, &f);
printf( "%d %u %c\n", k, val, f);
}
}