阅读量:166
stringstream 是 C++ 中的一个类,它位于 库中。这个类允许你使用流操作符 << 和 >> 来读取和写入字符串。你可以使用 stringstream 来解析字符串,例如提取子字符串、转换数据类型等。
下面是一些使用 stringstream 解析字符串的例子:
- 提取子字符串:
#include
#include
#include
int main() {
std::string input = "Hello, my name is John Doe.";
std::stringstream ss(input);
std::string name;
// 提取名字
getline(ss, name, ' '); // 使用空格作为分隔符
std::cout << "Name: " << name class="hljs-keyword">return 0;
}
- 转换数据类型:
#include
#include
#include
int main() {
std::string input = "123 45.67";
std::stringstream ss(input);
int age;
double salary;
// 转换整数和浮点数
ss >> age >> salary;
std::cout << "Age: " << age class="hljs-string">", Salary: " << salary class="hljs-keyword">return 0;
}
- 解析逗号分隔的值:
#include
#include
#include
int main() {
std::string input = "apple,banana,orange";
std::stringstream ss(input);
std::string fruit;
// 使用逗号作为分隔符
while (getline(ss, fruit, ',')) {
std::cout << "Fruit: " << fruit class="hljs-keyword">return 0;
}
这些例子展示了如何使用 stringstream 来解析字符串。你可以根据需要调整分隔符和数据类型,以便正确地解析你的字符串。