用std::stringstream举个例子
时间: 2023-06-09 13:02:55 浏览: 54
当然,我很乐意回答你的问题。可以使用 std::stringstream 对一个字符串进行操作。
例如,以下代码段演示了如何使用 std::stringstream 对字符串进行操作并将其输出到控制台:
```c++
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string s = "Hello, World! This is a test.";
stringstream ss(s);
string word;
while (ss >> word)
{
cout << word << endl;
}
return 0;
}
```
输出:
```
Hello,
World!
This
is
a
test.
```
此代码将字符串 s 中的单词逐个提取并打印到控制台上。
希望这个例子能够帮助您更好地理解 std::stringstream 的用法。
相关问题
std::vector<std::string> 转字符
如果你是要将`std::vector<std::string>`转换为一个单一的字符串,可以使用`std::stringstream`类进行操作。以下是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::vector<std::string> v = {"hello", "world", "!"};
std::stringstream ss;
for (const auto& str : v) {
ss << str << " ";
}
std::string result = ss.str();
std::cout << result << std::endl;
return 0;
}
```
这个程序将会输出 `hello world !`。在这个例子中,我们使用了一个 `std::stringstream` 对象来将所有的字符串连接起来,并且在每个字符串之间加上了空格。
std::string 使用分割成多个字符串
可以使用stringstream和getline函数来将一个字符串分割成多个子字符串。以下是一个例子:
```c++
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::string s = "apple,banana,orange";
std::stringstream ss(s);
std::vector<std::string> vec;
while (ss.good()) {
std::string substr;
getline(ss, substr, ',');
vec.push_back(substr);
}
for (auto str : vec) {
std::cout << str << std::endl;
}
return 0;
}
```
输出结果:
```
apple
banana
orange
```
在这个例子中,我们首先创建了一个字符串流对象ss,将原始字符串s传入其中。然后,我们使用getline函数从字符串流中逐个读取子字符串,以逗号作为分隔符。每次读取到一个子字符串后,我们将其存储到vector中。最后,我们遍历vector并输出每个子字符串。
注意,我们使用了good()函数来检查是否还有更多的子字符串需要读取。如果没有更多的子字符串,getline函数将返回false,while循环将终止。