一、基础概念
在进行string转对象之前,需要知道几个基础概念。首先,C++中有三种基本的用户自定义类型:
- 类(class)
- 结构体(structure)
- 联合(union)
这三种类型都可以用来定义数据结构。
其次,需要知道对象(object)的概念。对象是一个变量,它存储了一个特定类的数据。定义对象时,需要指定该对象的数据类型。
最后,需要理解string类型。string是C++中的一种特殊类型,它由若干个字符组成,可以用来存储字符串。
二、string转基本类型
在C++中,可以使用各种方法将string转换为基本类型,例如int、bool、double等。
1.将string转换为int类型
int stoi (const string& str, size_t* idx = 0, int base = 10);
该方法可以将一个以十进制表示的string转换为int类型。
示例:
#include <iostream> #include <string> using namespace std; int main() { string str = "1234"; int num = stoi(str); cout << num << endl; return 0; }
输出:
1234
2.将string转换为bool类型
bool stob (const string& str);
该方法可以将一个表示为字符串的bool值转换为bool类型。
示例:
#include <iostream> #include <string> using namespace std; int main() { string str = "true"; bool b = stob(str); cout << b << endl; return 0; }
输出:
1
3.将string转换为double类型
double stod (const string& str, size_t* idx = 0);
该方法可以将一个表示为字符串的double类型转换为double类型。
示例:
#include <iostream> #include <string> using namespace std; int main() { string str = "3.1415"; double pi = stod(str); cout << pi << endl; return 0; }
输出:
3.1415
三、string转自定义类型
1.将string转换为类对象
将string转换为类对象需要创建一个类型转换函数。
示例:
#include <iostream> #include <string> using namespace std; class Rectangle { public: Rectangle(int w, int h) : width(w), height(h) {} int area() const { return width * height; } private: int width; int height; }; Rectangle toRectangle(const string& str) { size_t pos = str.find(","); int w = stoi(str.substr(0, pos)); int h = stoi(str.substr(pos + 1)); Rectangle rect(w, h); return rect; } int main() { string str = "3,4"; Rectangle rect = toRectangle(str); cout << "Area: " << rect.area() << endl; return 0; }
输出:
Area: 12
2.将string转换为结构体对象
将string转换为结构体对象的方法类似于将string转换为类对象。
示例:
#include <iostream> #include <string> #include <sstream> using namespace std; struct Point { int x; int y; }; Point toPoint(const string& str) { Point p; stringstream ss(str); ss >> p.x; ss.ignore(); ss >> p.y; return p; } int main() { string str = "3,4"; Point p = toPoint(str); cout << "x: " << p.x << " y: " << p.y << endl; return 0; }
输出:
x: 3 y: 4
3.将string转换为联合类型
将string转换为联合类型需要依据具体的联合类型进行转换。
示例:
#include <iostream> #include <string> using namespace std; union myUnion { int i; char c; }; myUnion toUnion(const string& str) { myUnion u; if (str.length() == 1) { u.c = str[0]; } else { u.i = stoi(str); } return u; } int main() { string str = "A"; myUnion u = toUnion(str); if (str.length() == 1) { cout << "char: " << u.c << endl; } else { cout << "int: " << u.i << endl; } return 0; }
输出:
char: A
四、异常处理
在进行string转换时,可能会出现异常,例如string表示的数字超过了int类型的最大值,或者string无法表示为所需的目标类型等。此时,程序会抛出异常。为了避免程序崩溃,需要进行异常处理。
示例:
#include <iostream> #include <string> #include <stdexcept> using namespace std; int main() { string str = "2147483648"; try { int num = stoi(str); cout << num << endl; } catch (const out_of_range& e) { cerr << e.what() << endl; } return 0; }
输出:
stoi
以上便是关于string转对象的详解,可以根据需求进行转换。
原创文章,作者:CNBYN,如若转载,请注明出处:https://www.506064.com/n/361216.html