由to_string函数学习sprintf()及sscanf()函数的用法

今天看到VS里面的to_string()函数的实现,下面以int型参数的to_string为例介绍:

inline string to_string(int _Val)
    {   // convert int to string
    char _Buf[2 * _MAX_INT_DIG];

    _CSTD _TOSTRING(_Buf, "%d", _Val);
    return (string(_Buf));
    }

其中宏定义又有:

 #define _TOSTRING(buf, fmt, val)   \
    sprintf_s(buf, sizeof (buf), fmt, val)

下面简单看下sprintf()函数(参考c++官方文档):

int sprintf ( char * str, const char * format, ... );
str
Pointer to a buffer where the resulting C-string is stored.
The buffer should be large enough to contain the resulting string.

format
C string that contains a format string that follows the same specifications as format in printf (see printf for details).

... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

返回值:
On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string.
On failure, a negative number is returned.

例子:

/* sprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}

运行结果:
[5 plus 3 is 8] is a string 13 chars long

下面我来说说,sprintf()是个c的函数,当然c++兼容c也可以用,c语言在stdio.h中,c++在cstdio中
str为要写入的字符串;format为格式化字符串,与printf()函数相同;argument为变量。
成功则返回写入str的字符串长度,失败则返回-1,错误原因存于errno 中。

sprintf的作用是将一个格式化的字符串输出到一个目的字符串中,而printf是将一个格式化的字符串输出到屏幕。sprintf的第一个参数应该是目的字符串,如果不指定这个参数,执行过程中出现 “该程序产生非法操作,即将被关闭….”的提示。

sprintf()最常见的应用之一莫过于把整数打印到字符串中,如:
sprintf(s, “%d”, 123); //把整数123打印成一个字符串保存在s中
sprintf(s, “%8x”, 4567); //小写16进制,宽度占8个位置,右对齐
下面简单给两个例子:

//打印字母a的ASCII值
#include <stdio.h>
main()
{
    char a = 'a';
    char buf[80];
    sprintf(buf, "The ASCII code of a is %d.", a);
    printf("%s", buf);
}

输出:The ASCII code of a is 97.

//产生10个100以内的随机数并输出
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
    char str[100];
    int offset =0;
    int i=0;
    srand(time(0));  // *随机种子
    for(i = 0;i<10;i++)
    {
        offset+=sprintf(str+offset,"%d,",rand()%100);  // 格式化的数据写入字符串
    }
    str[offset-1]='\n';
    printf(str);
    return 0;
}

输出:74,43,95,95,44,90,70,23,66,84

既然学习了sprintf函数,那么顺便看看sscanf函数吧,同样先看官方文档

int sscanf ( const char * s, const char * format, ...);
s
C string that the function processes as its source to retrieve the data.
format
C string that contains a format string that follows the same specifications as format in scanf (see scanf for details).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the interpretation of the extracted characters is stored with the appropriate type.
There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function.

返回值:
On success, the function returns the number of items in the argument list successfully filled. This count can match the expected number of items or be less (even zero) in the case of a matching failure.
In the case of an input failure before any data could be successfully interpreted, EOF is returned.

例子:

/* sscanf example */
#include <stdio.h>

int main ()
{
  char sentence []="Rudolph is 12 years old";
  char str [20];
  int i;

  sscanf (sentence,"%s %*s %d",str,&i);//注意这里以空格分隔
  printf ("%s -> %d\n",str,i);

  return 0;
}

输出:Rudolph -> 12

下面我来说说,参数str为要读取数据的字符串;format为用户指定的格式;argument为变量,用来保存读取到的数据。
sscanf()与scanf()类似,都是用于输入的,只是scanf()以键盘(stdin)为输入源,sscanf()以固定字符串为输入源。
成功则返回参数数目,失败则返回-1,错误原因存于errno 中。

例子:

//从指定的字符串中读取整数和小写字母
#include <stdio.h>
int main(void)
{
    char str[100] ="123568qwerSDDAE";
    char lowercase[100];
    int num;
    sscanf(str,"%d %[a-z]", &num, lowercase);
    printf("The number is: %d.\n", num);
    printf("The lowercase is: %s.", lowercase);
    return 0;
}

输出:

The number is: 123568.
The lowercase is: qwer.

可以看到format参数有些类似正则表达式(当然没有正则表达式强大,复杂字符串建议使用正则表达式处理),支持集合操作,例如:
%[a-z] 表示匹配a到z中任意字符,贪婪(尽可能多的匹配)
%[aB’] 匹配a、B、’中一员,贪婪
%[^a] 匹配非a的任意字符,贪婪

另外,format不仅可以用空格界定字符串,还可以用其他字符界定,可以实现简单的字符串分割(更加灵活的字符串分割请使用strtok())。例如:

sscanf("2006:03:18", "%d:%d:%d", a, b, c);
sscanf("2006:03:18 - 2006:04:18", "%s - %s", sztime1, sztime2);
C语言中的string函数主要包括字符串的处理函数和字符串的操作函数。 字符串的处理函数主要有以下几个: 1. strlen:用于计算字符串的长度,即包含的字符数目。 2. strcpy:用于将一个字符串复制到另一个字符串中。 3. strcat:用于将两个字符串连接起来。 4. strcmp:用于比较两个字符串的大小关系。 5. strchr:用于在一个字符串中查找指定字符的位置。 6. strstr:用于在一个字符串中查找指定子串的位置。 字符串的操作函数主要有以下几个: 1. sprintf:用于将格式化的数据写入字符串中。 2. sscanf:用于从字符串中读取格式化的数据。 3. strtok:用于将一个字符串按照指定的分隔符进行分割。 4. strncmp:用于比较两个字符串的前n个字符的大小关系。 5. strncpy:用于将一个字符串的部分内容复制到另一个字符串中。 6. memset:用于给字符串的指定范围内的每个字符赋予相同的值。 这些函数可以帮助我们在C语言中方便地处理字符串,实现字符串的复制、连接、比较、查找等操作。通过这些函数,我们可以更高效地处理文本数据,提高代码的可读性和可维护性。 需要注意的是,使用这些函数时要确保输入的参数合法,以避免内存越界等错误。同时,字符串的内存空间需要提前分配好,以免出现不可预知的问题。在实际编程中,我们需要灵活运用这些函数,结合具体需求,进行字符串的处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值