Stringstream 与 C++ 中的类型转换

Stringstream vs. type casting in C++

使用 stringstream 从字符串中提取整数值与简单地使用显式值转换来更改类型有何不同?

示例:

string a = "1234";
int x;
x= int (a);

对比

string a = "1234";
int x;
stringstream (a) >> x;

嗯,主要区别在于:

string a = "1234";
int x;
x= int (a);

不编译,没有从 std::string 到 int 的转换。将 std::string 转换为 int 的现代方法是使用 stoi 函数,但要小心使用它,因为它会抛出 "x1234" 但会很高兴地解析:“1234x”。