解析一个简单的字符串 [英] Parsing a simple string

查看:52
本文介绍了解析一个简单的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,


我正在尝试解析一个字符串,我对结果感到惊讶(*)

使用时:

sscanf(s,%03u%c,& val,& f);

如果找到的数字小于3位,则不应该报告

那个?


谢谢

Mathieu

(*)

# include< stdio.h>


void parse(const char * s)

{

unsigned int val;

char f;

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

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

}


int main()

{

// 21年:

parse(" 021Y");

// 1年(无效)

parse(" 0-1Y");


返回0;

}

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 ?

Thanks
Mathieu
(*)
#include <stdio.h>

void parse(const char *s)
{
unsigned int val;
char f;
int k = sscanf(s, "%03u%c", &val, &f);
printf( "%d %u %c\n", k, val, f);
}

int main()
{
// 21 years:
parse( "021Y" );
// -1 year (invalid)
parse( "0-1Y" );

return 0;
}

推荐答案

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);
}
}


这篇关于解析一个简单的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆