C++输出任意变量为字符串的接口
时间: 2023-12-27 21:02:08 浏览: 90
字符串变量的赋值-c++数组学习资料
在C++中,可以使用`std::to_string()`函数将各种数据类型转换为字符串,例如:
```cpp
int num = 123;
std::string str_num = std::to_string(num);
std::cout << str_num << std::endl;
```
此外,对于自定义类型,需要重载`<<`运算符来实现输出为字符串,例如:
```cpp
class Person {
public:
std::string name;
int age;
friend std::ostream& operator<<(std::ostream& os, const Person& p) {
os << "Name: " << p.name << ", Age: " << p.age;
return os;
}
};
Person p {"Tom", 20};
std::cout << p << std::endl; // 输出:Name: Tom, Age: 20
```
阅读全文