About the usage of c_str() in sscanf, sprintf, fsprintf, fscanf and string

sscanf (string to number)

The sscanf function prototype is int sscanf(const char str, const char format,...). The string of the parameter str is converted and formatted according to the parameter format string, and the converted result is stored in the corresponding parameter. The specific functions are as follows:

(1) Extract data from the string according to the format. Such as extracting integers, floating-point numbers and strings from the string.

(2) Take a string of specified length

(3) Get the character string up to the specified character

(4) Take a string containing only the specified character set

(5) Get the character string up to the specified character set

#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 (number is converted to string)

The sprintf function prototype is int sprintf(char str, const char format,...). The function is to format a string, and the specific functions are as follows:

(1) Convert digital variables to character strings.

(2) Get the hexadecimal and octal strings of integer variables.

(3) Concatenate multiple strings.

#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;
}

About 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;
}

This is to be compatible with the C language. There is no string type in the C language, so the string object must be converted into the string style in c through the member function c_str() of the string class object.

Note: Be sure to use the strcpy() function to manipulate the pointer returned by the method c_str().

Guess you like

Origin blog.csdn.net/qq_45812180/article/details/114637664