c/c++ 结构体转化为字符串
时间: 2023-08-11 13:29:59 浏览: 374
将一个结构体转化为字符串,可以使用 sprintf 函数或者 stringstream 类。下面是一个使用 sprintf 函数的例子:
```c
#include <stdio.h>
struct Student {
char name[20];
int age;
float score;
};
int main() {
struct Student stu = {"Tom", 18, 90.5};
char str[100];
sprintf(str, "Name: %s, Age: %d, Score: %.2f", stu.name, stu.age, stu.score);
printf("%s\n", str);
return 0;
}
```
输出结果:
```
Name: Tom, Age: 18, Score: 90.50
```
使用 stringstream 类的例子:
```c++
#include <iostream>
#include <sstream>
struct Student {
std::string name;
int age;
float score;
};
int main() {
struct Student stu = {"Tom", 18, 90.5};
std::stringstream ss;
ss << "Name: " << stu.name << ", Age: " << stu.age << ", Score: " << stu.score;
std::cout << ss.str() << std::endl;
return 0;
}
```
输出结果:
```
Name: Tom, Age: 18, Score: 90.5
```
阅读全文