介绍
本文总结C/C++中字符串类型和整型、浮点型转换的方法。包括C语言中函数sscanf
、sprintf
和C++中类stringstream
的使用。
C语言
字符串->数据
sscanf
sscanf
函数的声明为int sscanf(const char *str, const char *format, ...)
,用于从字符串格式化输入,可以实现字符串到任意进制整数或浮点数的转换。
str
: C语言字符串,表示输入的源字符串。format
: C语言字符串,规定读取源字符串的方式。常用的格式符如下所示。%c
: 读取单个字符。%s
: 读取字符串。%d
: 读取整数。%f
: 读取浮点数。%o
: 读取整数并转换成八进制。%x
: 读取整数并转换成小写十六进制。%X
: 读取整数并转换成大写十六进制。
示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int day, year;
char weekday[20], month[20];
char str[100];
strcpy(str, "Saturday March 25 1989");
sscanf(str, "%s %s %d %d", weekday, month, &day, &year);
printf("%s %s %d %d\n", weekady, month, day, year);
return(0);
}
输出结果为
Saturday March 25 1989
数据->字符串
sprintf
sprintf
的声明为int sprintf(char *str, const char *format, ...)
,用于发送格式化输出到str指向的字符串,可以实现数据类型到字符串的转换。
str
: C语言字符串,表示需要输出到的目的字符串。format
: C语言字符串,规定输出到目的字符串的方式。常用的格式符如下所示。%c
: 输出单个字符。%s
: 输出字符串。%d
: 输出整数。%f
: 输出浮点数。%o
: 输出整数并转换成八进制。%x
: 输出整数并转换成小写十六进制。%X
: 输出整数并转换成大写十六进制。
示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int day = 25;
int year = 1989;
char weekday[20], month[20];
char str[100];
strcpy(weekday, "Saturday");
strcpy(month, "Match");
sprintf(str, "%s %s %d %d", weekday, month, day, year);
printf("%s\n", str);
return(0);
}
输出结果为
Saturday March 25 1989
C++
C++在头文件sstream
中定义了类stringstream
,可以用来进行流的输入输出操作。
字符串->数据
示例
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
stringstream ss;
int data;
string str = "924";
ss << dec << str;
// 转换成十六进制
// ss << hex << str;
// 转换成八进制
//ss << oct << str;
ss >> data;
cout << data;
}
输出结果为
924
数据->字符串
示例
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
stringstream ss;
int data = 924;
string str;
ss << dec << data;
// 转换成十六进制
// ss << hex << data;
// 转换成八进制
//ss << oct << data;
ss >> str;
cout << str;
}
输出结果为
924
至此,C/C++字符串转换总结完毕。