[C语言]字符串与其他类型间的转换

Plux posted @ 2011年6月06日 16:26 in C/C++ with tags c/c++ , 2422 阅读

字符串->其他类型:sscanf(const char *src, const char *format, ... )

这个函数和scanf(const char *format, ...)类似,但不同的是,sscanf()是把字符串src当作输入,然后从中提取需要的信息的。所以,事实上format参数的运用和我们从标准输入(键盘)那里获取参数是相似的。

例如:

由字符串提取整数(十进制):

char *src="2"; int i;
sscanf(src, "%d", &i); /* i = 2 */

从字符串提取浮点数:

char *src="2.2"; float f;
sscanf(src, "%f", &f); /* f = 2.2 */

从字符串提取字符串:

char *src="abc def"; char a[4], b[4];
sscanf(src, "%s %s", a, b); /* a="abc". b="def" */

这个是比较有意思的应用。这样,我们就可以很方便地分割字符了。

而使用这个函数时,不需注意后面的参数是指针而不是整数或者其他数值类型。


其他类型->字符串:sprintf(const char *dest, const char *format, ...)

这个函数和sscanf是相对应的。因此,可以类比printf()的用法来得出这个函数的用法,就是从把后文format的内容复制到src中而不是标准输出而已。

例如:

十进制整数到字符串:

char dest[3]; int i=3;
sprintf(dest, "%d", i); /* dest = "3"; */

浮点数到字符串:

char dest[5]; float f=3.3f;
sprintf(dest, "%f", f); /* dest = "3.3" */

字符串到字符串:

char dest[10]; char *a="abc", *b="def";
sprintf(dest, "%s %s", a, b); /* dest = "abc def" */

这样也可以当作字符串合并函数用~

而使用sprintf()时必须注意目标字符串的长度。

以上的仅仅列举了常用的一些类型转换,至于其他类型,只要修改格式中的%x就好了(x替换为其他类型的代表字符,叫做类型转换符吧,另外注意‘x’本身其实也代表一种类型)。作为一个参考的文档,把Linux Programmer's Manual上关于sscanf()和sprintf()的文档也翻译一下吧~

类型转换符:(就是修饰在‘%’后面的字符,作为后面传入参数的类型提示。)

  • d - 十进制整数,对应int类型指针
  • i - 整数,对应int类型;与d不同的是,如果字符串中的整数以‘0x’等暗示进位制的前缀时,它会自动识别为该进制下的整数。
  • o - 八进制整数,对应int类型指针
  • u - 无符号十进制整数,对应unsigned int类型指针
  • x - 十六进制整数,对应int类型指针
  • f - 浮点数,对应float类型指针
  • s - 连续字符串(没有空格分开),对应char的指针
  • c - 指定长度的字符串,例如:10c读取10个字符到字符串中。对应char指针
  • [] - 匹配正则表达式……
  • ……

 

类型修饰符:(就是在前面类型转换符前面加的修饰符)

  • h - 修饰短整数
  • l - 长整数
  • L - 更精确的double类型(也就是long double)
  • ……

另外,这两个函数就存在于stdio.h中,属于标准函数。更详细的内容,例如正则表达式的使用,参见Linux Programmer's Manual……

 

토토사이트넷마블 说:
Dec 04, 2023 01:45:35 PM

This method is actually aesthetically truly the most suitable. Every one associated with tiny illustrates tend to be meant by way of numerous history abilities. I suggest the program quite a bit. 

아인카지노주소 说:
Dec 04, 2023 02:19:16 PM

When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four e-mails with the same comment. Is there any way you can remove people from that service? Many thanks!

부띠끄 도메인주소 说:
Dec 04, 2023 02:22:04 PM

I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article so only.Thanks!

벳365우회주소 说:
Dec 04, 2023 02:42:27 PM

Howdy! Would you mind if I share your blog with my twitter group? There’s a lot of people that I think would really enjoy your content. Please let me know. Thanks

베트맨토토모바일 说:
Dec 04, 2023 03:00:03 PM

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own Blog Engine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it. 

메이저놀이터코드 说:
Dec 04, 2023 03:31:20 PM

This was a truly heartwarming post. I told my friends that you have great content. Solving some problems with friends helped me a lot. Thank you for your efforts. 

해외놀이터검증 说:
Dec 04, 2023 04:44:06 PM

Hello! I’ve been following your blog for a while now and finally got the courage to go ahead and give you a shout out from  Kingwood Texas! Just wanted to mention keep up the good work! 

메이저놀이터추천 说:
Dec 04, 2023 04:48:04 PM

Positive points apparel it all check to two different females: old Zune company owners that focusing on an upgrade, and individuals seeking to determination between a Microsoft zune and an ipod devices. (San francisco spa battlers worthwhile considering about, for instance the The Personal stereo By, however , Truly hope guarantees you sufficient statistics that helps make an informed resolution with the Zune instead of manufacturers other than ipod range same.)

먹튀검증 说:
Dec 04, 2023 05:14:15 PM

Nice blog! Only problem  is i’m running Firefox on Debian, and the site is looking a little.. weird! Perhaps you may want to test it to see for yourself.

슬롯머신 说:
Dec 04, 2023 05:20:22 PM

This method is usually successfully definitely best option. Every single one connected with incredibly tiny features usually are supposed by using quite a few historical past ability. I might suggest the software program tremendously. 

메이저파워볼사이트 说:
Dec 04, 2023 05:40:28 PM

This method is actually aesthetically truly the most suitable. Every one associated with tiny illustrates tend to be meant by way of numerous history abilities. I suggest the program quite a bit. 

메이저사이트 说:
Dec 04, 2023 06:20:07 PM

Hiya, I am really glad I have found this info. Nowadays bloggers publish just about gossips and net and this is actually annoying. A good blog with interesting content, that is what I need. Thanks for keeping this web site, I’ll be visiting it. Do you do newsletters? Can not find it.

토토사이트홍보 说:
Dec 04, 2023 06:23:07 PM

When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four e-mails with the same comment. Is there any way you can remove people from that service? Many thanks!

토토커뮤니티 说:
Dec 04, 2023 06:27:50 PM

I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article so only.Thanks!

메이저놀이터 说:
Dec 04, 2023 06:50:26 PM

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own Blog Engine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it. 

보증업체 说:
Dec 04, 2023 06:53:44 PM

Howdy! Would you mind if I share your blog with my twitter group? There’s a lot of people that I think would really enjoy your content. Please let me know. Thanks

안전공원 说:
Dec 04, 2023 06:59:52 PM

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own Blog Engine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it. 

파워사다리추천 说:
Dec 04, 2023 07:18:32 PM

Truly, this article is really one of the very best in the history of articles. I am a antique ’Article’ collector and I sometimes read some new articles if I find them interesting. And I found this one pretty fascinating and it should go into my collection. Very good work!

토토사이트추천 说:
Dec 04, 2023 07:32:02 PM

It's really nice and meanful. it's really cool blog. Linking is very useful thing.you have really helped lots of people who visit blog and provide them usefull information 

먹튀팀즈 说:
Dec 04, 2023 07:40:35 PM

Positive points apparel it all check to two different females: old Zune company owners that focusing on an upgrade, and individuals seeking to determination between a Microsoft zune and an ipod devices. (San francisco spa battlers worthwhile considering about, for instance the The Personal stereo By, however , Truly hope guarantees you sufficient statistics that helps make an informed resolution with the Zune instead of manufacturers other than ipod range same.)

코인카지노주소 说:
Dec 04, 2023 07:53:41 PM

Individuals possess using a amazing openings. After i sanity unquestionably quarry them additionally personally recommend to assist the actual buddys. My personal company is actually self-possessed lots of people solve perhaps end up being benefited with this particular globe.

승인전화없는토토 说:
Dec 04, 2023 07:54:46 PM

significantly in which saintly however, I adore kinds input moreover pleasurable images may very well be factor personss unfavorable enjoy currently being defrent intellect complete poeple,

먹튀폴리스검증업체 说:
Dec 04, 2023 07:55:44 PM

This is the reason it really is greater you could important examination before creating. It will be possible to create better write-up like this.

보증업체 说:
Dec 04, 2023 07:59:07 PM

A person essentially help to make seriously articles I would state. This is the first time I frequented your website page and thus far? I surprised with the research you made to make this particular publish incredible. Fantastic job! 

바카라사이트 说:
Dec 04, 2023 08:06:02 PM

Hello! I’ve been following your blog for a while now and finally got the courage to go ahead and give you a shout out from  Kingwood Texas! Just wanted to mention keep up the good work! 

에볼루션카지노가입 说:
Dec 04, 2023 08:14:46 PM

It's really nice and meanful. it's really cool blog. Linking is very useful thing.you have really helped lots of people who visit blog and provide them usefull information 

탐험대 说:
Dec 04, 2023 08:16:56 PM

To be sure with all your thoughts here and I love your blog! I’ve bookmarked it to ensure that I am able to come back & read more in the future.

사설토토 说:
Dec 04, 2023 08:18:39 PM

This is the reason it really is greater you could important examination before creating. It will be possible to create better write-up like this.

축구실시간배팅 说:
Dec 04, 2023 08:23:40 PM

In all honesty, it is the sort of data I've for some time been attempting to find. It matches to my necessities a ton. Much thanks to you for composing this data.

먹튀검증 说:
Dec 04, 2023 08:32:43 PM

This is the reason it really is greater you could important examination before creating. It will be possible to create better write-up like this.

카지노 说:
Dec 04, 2023 08:34:09 PM

kings Resort Dandeli is the best Luxury resort in Dandeli. Discover the best of Dandeli resorts and packages at Kings Resort. Your gateway to nature & paradise awaits.

바카라사이트 说:
Dec 04, 2023 09:01:10 PM

Thank you for the auspicious writeup. It in fact was an amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate

안전토토사이트 说:
Dec 04, 2023 09:29:10 PM

Lotteries have a broad appeal due to the potential for life-changing winnings. By merging slots with lottery themes, casinos and game developers can attract a wider audience of players who may not have been traditional slot enthusiasts.Lotteries are typically games of pure chance, whereas slot machines can involve some skill in terms of betting strategies and bonus features. Combining

เว็บพนันบอล 说:
Dec 04, 2023 09:42:14 PM

This is a great article, Given such a great amount of information in it, These kind of articles keeps the clients enthusiasm for the site, and continue sharing more ... 

배트맨단폴 说:
Dec 04, 2023 10:21:39 PM

I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article so only.Thanks!

먹튀검증 说:
Jan 15, 2024 05:09:54 PM

All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks

온라인카지노 说:
Jan 16, 2024 05:14:02 PM

"Thank you for sharing your info. I really appreciate
your efforts and I will be waiting for your further
post thanks once again.

"


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter