int snprintf(char *str, size_t size, const char *format, ...);
The functions snprintf() write at most size bytes (including the terminating null byte ('\0')) to str
即snprintf这个函数按照format格式最多将size个字符写入到str中,其中size个字符已经包括了结束符。
很多时候,总没记住size这个参数是否包含结束符'\0',一般都填入size的参数就填str的大小减1了,这样肯定没错,只不过缓冲区中有一位肯定都用不上了。其实该函数内部已经对这些东西进行考虑了,我们只需要填入str的实际size就可以。
scanf()函数接收输入数据时,遇以下情况结束一个数据的输入: ① 遇空格、“回车”、“跳格”`,Tab键键。 ② 遇宽度结束。 ③ 遇非法输入。
比如:
所以:
scanf("%s",str);改成:
scanf("%[^\n]",comm_buf); getchar();读到'\n'结束读取,getchar()吸取换行符。很重要,不然scanf 无法循环的读入
scanf()是不可以读入空格的,他是以空格,tab,和回车为结束符的,而gets是不以空格为结束符的,他可以读入空格的,他只以回车和tab键为结束符,真的想吐槽一下这个函数。
代码实例:
#include <stdlib.h> #include <stdio.h> int main(void) { int number = -12345; char string[32]; itoa(number, string, 10); printf("integer = %d\nstring = %s\n", number, string); return 0; }运行结果:
功能:把一个整数转换成字符串。
说明:itoa 并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。标准库中有sprintf,功能比这个更强,用法跟printf类似:
char str[255]; sprintf(str, "%x", 100); //将100转为16进制表示的字符串。