输入一行带逗号的字符按逗号分割
时间: 2023-09-16 15:08:51 浏览: 40
可以使用C++中的字符串流 stringstream 来进行分割。具体步骤如下:
1. 包含头文件
```c++
#include <sstream>
#include <string>
#include <vector>
```
2. 定义输入字符串并读入
```c++
string input = "apple,banana,orange";
```
3. 创建stringstream对象并读入输入字符串
```c++
stringstream ss(input);
```
4. 定义vector存储分割后的字符串
```c++
vector<string> result;
```
5. 使用getline()函数按照逗号分割字符串
```c++
string item;
while (getline(ss, item, ',')) {
result.push_back(item);
}
```
完整代码如下:
```c++
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main() {
string input = "apple,banana,orange";
stringstream ss(input);
vector<string> result;
string item;
while (getline(ss, item, ',')) {
result.push_back(item);
}
for (int i = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
return 0;
}
```
输出结果为:apple banana orange