C和C++中的字符串与数字转换函数


前言:

      今天开始想要好好补补程序,开始看老早就买了的《算法入门经典》,发现前面几章对字符串的处理较多,搜罗了一下别人的博客,整理到这上面来。

       C语言中常用的字符串和数字转换函数是 sscanfsprintf,C++中引入了流的概念,通过流来转换字符串和数字就方便了许多。


1.sprintf函数

sprintf函数原型为 int sprintf(char *str, const char *format, ...)。作用是格式化字符串,具体功能如下所示:
       (1)将数字变量转换为字符串。
  (2)得到整型变量的16进制和8进制字符串。
  (3)连接多个字符串。

下面贴出代码实例:
#include<stdio.h>
#include<iostream>
using namespace std;
int main(){
    char str[256]={0};
    int data=1024;
    //将data转换为字符串
    sprintf(str,"%d",data);
    cout<<str<<endl;
    //获取data的16进制
    sprintf(str,"0x%X",data);
     cout<<str<<endl;
    //获取data的八进制
    sprintf(str,"0%o",data);
     cout<<str<<endl;
    const char *s1="Hello";
    const char *s2="World";
    //连接s1和s2
    sprintf(str,"%s %s",s1,s2);
    cout<<str<<endl;
    return 0;}
编辑过程中都忘记了C++结尾要用分号了,伤感……


2.sscanf()函数

sscanf函数原型为int sscanf(const char *str, const char *format, ...)。

将参数str的字符串根据参数format字符串来转换并格式化数据,转换后的结果存于对应的参数内。具体功能是从字符串中读取与指定格式相符的数据:
 char buf[512];
    sscanf("123456","%s",buf);
    printf("%s\n",buf);//输出结果为123456
    //取指定长度的字符串
    sscanf("123456","%4s",buf);
    printf("%s\n",buf);//结果为1234
    //取到指定字符为止的字符串
    sscanf("123456 abcdef","%[^ ]",buf);
    printf("%s\n",buf);//取遇到空格为止的字符串
    //取仅包含指定字符集的字符串
    sscanf("123456abcdefBCDEF","%[1-9a-z]",buf);
    printf("%s\n",buf);//结果仅包含数字和小写字母
    //取到指定字符集为止的字符串,与取到空格为止相似
     sscanf("123456abcdefBCDEF","%[^A-Z]",buf);
    printf("%s\n",buf);//取到大写字母为止
    //给定一个字符串iios/12DDWDFF@122,获取 / 和 @ 之间的字符串,
    //先将 "iios/"过滤掉,再将非'@'的一串内容送到buf中
    sscanf("iios/12DDWDFF@122","%*[^/]/%[^@]",buf);
     printf("%s\n",buf);
     //给定一个字符串““hello, world”,仅保留world。
     //(注意:“,”之后有一空格)
     sscanf("hello, world","%*s%s",buf);
     printf("%s\n",buf);
     //%*s表示第一个匹配到的%s被过滤掉,即hello被过滤了
     //如果没有空格则结果为NULL
%[ ] 类似于正则表达式 该函数中读取的字符串是默认以空格来分割的,如果不以空格来分割,可以用%[],例如:
sscanf("2006:03:18 - 2006:04:18", "%[0-9,:] - %[0-9,:]", sztime1, sztime2); 

3.stringstream类

<sstream>库定义了三种类:istringstream、ostringstream和stringstream, 分别用来进行流的输入、输出和输入输出操作。该类除了处理字符串外还可以进行任意类型的转换。具体看实例代码:
template<typename out_type,typename in_type>
out_type convert(const in_type&t){
    stringstream stream;
    stream<<t;//向流中传值
    out_type result;//这里存储转换结果
    stream>>result;
    return result;
}
 string s="12 34 56 # 788";
     stringstream ss;
     ss<<s;
     while(ss>>s){
        //cout<<s<<endl;
        int val=convert<int>(s);
        cout<<val<<endl;
     }
运行结果如下:

可见流输出时也是以空格来分割字符串的。

实验过程中用的codeblocks,VS太大跑起来慢,VC莫名运行不起来,发现codeblocks还可以。
Ctrl+shift+c可以快速注释掉多行
Ctrl+shift+x可以删除注释。
在这里做个笔记!

猜你喜欢

转载自blog.csdn.net/S_J_Huang/article/details/75006434