zoukankan      html  css  js  c++  java
  • C++中的 istringstream 的用法

    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

    输出结果如下:
    输出结果

                                    </div>
    无欲则刚 关心则乱
  • 相关阅读:
    Web中的通配符
    EJB版本
    package-info.java
    dynamic web module version
    深入解析和反思携程宕机事件
    Ubuntu 环境下使用cronolog 切割Tomcat日志
    ubuntu环境下cassandra安装配置
    zabbix自定义触发器语法
    zabbix系统邮件告警Python脚本
    Ubuntu14.04下zabbix2.4.5 源码编译安装
  • 原文地址:https://www.cnblogs.com/xjyxp/p/11515450.html
Copyright © 2011-2022 走看看