关于sscanf,sprintf,fsprintf,fscanf和string中c_str()的用法

sscanf(字符串转数字)

sscanf函数原型为int sscanf(const char str, const char format,…)。将参数str的字符串根据参数format字符串来转换并格式化数据,转换后的结果存于对应的参数内。具体功能如下:

(1)根据格式从字符串中提取数据。如从字符串中取出整数、浮点数和字符串等。

(2)取指定长度的字符串

(3)取到指定字符为止的字符串

(4)取仅包含指定字符集的字符串

(5)取到指定字符集为止的字符串

#include<iostream>

uisng namespace std;

int main(){
    
    

char str[]="1234321";
int a;
sscanf(str,"%d",&a);
......1.......
char str[]="123.321";
double a;
sscanf(str,"%lf",&a);
......2......
char str[]="AF";
int a;
sscanf(str,"%x",&a); //16进制转换成10进制

//另外也可以使用atoi(),atol(),atof().
}

#include <iostream>
#include <cstdio>
using namespace std;
int main() {
    
    
    char c[50] = "123";
    int a;
    sscanf(c, "%d", &a); // 不要忘记 “&”
    int b = 567;
    sprintf(c, "%d", b);
    cout << a << endl << c;
    return 0;
}
 
/*
sscanf将字符数组转换为数字,输入到数字变量中
sprintf将数字转换为字符数组,输出到字符数组变量中
*/

sprintf(数字转化为字符串)

sprintf函数原型为 int sprintf(char str, const char format,…)。作用是格式化字符串,具体功能如下所示:

(1)将数字变量转换为字符串。

(2)得到整型变量的16进制和8进制字符串。

(3)连接多个字符串。

#include<iostream>

uisng namespace std;

int main(){
    
    
    char str[256] = {
    
     0 };
    int data = 1024;

    //将data转换为字符串
    sprintf(str,"%d",data);

    //获取data的十六进制
    sprintf(str,"0x%X",data);

    sprintf(str,"%x",data);//10进制转换成16进制,如果输出大写的字母是sprintf(str,"%X",a)

    //获取data的八进制
    sprintf(str,"0%o",data);


    const char *s1 = "Hello";
    const char *s2 = "World";
    //连接字符串s1和s2
    sprintf(str,"%s %s",s1,s2);
    cout<<str<<endl; 
    return 0;
}

关于c_str()

# include<iostream>
# include<cstring>
# include<cstdio>
# include<algorithm>
using namespace std;

int main()
{
    
    
	//假设输入格式为17:21:07 00:31:46 (+1),取其中的数字
	string line;
	int h1, m1, s1, h2, m2, s2, d;
    sscanf(line.c_str(), "%d:%d:%d %d:%d:%d (+%d)", &h1, &m1, &s1, &h2, &m2, &s2, &d);
    //c_str()函数返回一个指向正规C字符串的指针常量,因为sscanf只能接收c类型的字符串
	return 0;
}

这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。

注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针。

猜你喜欢

转载自blog.csdn.net/qq_45812180/article/details/114637664