码迷,mamicode.com
首页 > 编程语言 > 详细

C++中的 istringstream 的用法

时间:2019-09-12 23:50:41      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:ios   self   unset   cap   std   blog   pat   follow   使用   

C++分割带逗号的字符串

我们知道,C++默认通过空格(或回车)来分割字符串输入,即区分不同的字符串输入。但是有时候,我们得到的字符串是用逗号来分割的,给我们使用者带来极大的不便。
那么,有什么办法能更加方便的使用这些字符串呢?其实,C++提供了一种方法(我目前所知道的)来解决这个问题。

1. 解决方法

C++提供了一个类 istringstream ,其构造函数原形如下:

istringstream::istringstream(string str);
  • 1

它的作用是从 string 对象 str 中读取字符。
那么我们可以利用这个类来解决问题,方法如下:
第一步:接收字符串 s
第二步:遍历字符串 s ,把 s 中的逗号换成空格;
第三步:通过 istringstream 类重新读取字符串 s
注意, istringstream 这个类包含在库 < sstream > 中,所以头文件必须包含这个库。

2. 代码实现

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
    string s = "ab,cd,e,fg,h";
    int n = s.size();
    for (int i = 0; i < n; ++i){
        if (s[i] == ‘,‘){
            s[i] = ‘ ‘;
        }
    }
    istringstream out(s);
    string str;
    while (out >> str){
        cout << str <<‘ ‘;
    }
    cout << endl;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

输出结果如下:
技术图片

C++中的 istringstream 的用法

标签:ios   self   unset   cap   std   blog   pat   follow   使用   

原文地址:https://www.cnblogs.com/xjyxp/p/11515450.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!