C++ sstream以及其他的字符串处理

这篇文章是借鉴转载了其他人的文章合起来的,作为自己忘记待查的文章
参考的有:
c++ stringstream(老好用了)
C++ stringstream介绍,使用方法与例子

一、C语言的方法sscanf、sprintf

1.1 常见的格式串

	%% 印出百分比符号,不转换。
  %c 整数转成对应的 ASCII 字元。
  %d 整数转成十进位。
  %f 倍精确度数字转成浮点数。
  %o 整数转成八进位。
  %s 整数转成字符串。
  %x 整数转成小写十六进位。
  %X 整数转成大写十六进位。
  %n sscanf(str, "%d%n", &dig, &n),%n表示一共转换了多少位的字符

1.2 sprintf函数

sprintf函数原型为 int sprintf(char *str, const char *format, …)。作用是格式化字符串,具体功能如下所示:

(1)将数字变量转换为字符串。

(2)得到整型变量的16进制和8进制字符串。

(3)连接多个字符串。

int main(){
    
    
    char str[256] = {
    
     0 };
    int data = 1024;
    //将data转换为字符串
    sprintf(str,"%d",data);
    //获取data的十六进制
    sprintf(str,"0x%X",data);
    //获取data的八进制
    sprintf(str,"0%o",data);
    const char *s1 = "Hello";
    const char *s2 = "World";
    //连接字符串s1和s2
    sprintf(str,"%s %s",s1,s2);
    cout<<str<<endl; 
    return 0;
} 

1.3 sscanf函数

sscanf函数原型为int sscanf(const char *str, const char *format, …)。将参数str的字符串根据参数format字符串来转换并格式化数据,转换后的结果存于对应的参数内。具体功能如下:

(1)根据格式从字符串中提取数据。如从字符串中取出整数、浮点数和字符串等。

(2)取指定长度的字符串

(3)取到指定字符为止的字符串

(4)取仅包含指定字符集的字符串

(5)取到指定字符集为止的字符串

当然,sscanf可以支持格式串"%[]"形式的,有兴趣的可以研究一下。
  
其中浮点数的输出可以参考C/C++进制转换和输出格式

int main(){
    
    
    char s[15] = "123.432,432";
    int n;
    double f1;
    int f2;
    sscanf(s, "%lf,%d%n", &f1, &f2, &n);
    cout<<f1<<" "<<f2<<" "<<n;
    return 0;
} 

二、C++的方法

2.1 sstream

重头戏来了,传说中字符流。导入的模式是

#inculde<sstream>
其中<sstram>定义了三种类:
1、istringstream 输入流
2、ostringstream输出流 
3、stringstream输入输出流

其中几种常用的方式是:

#include<sstream>
#include<string>
#include<iostream>
using namespace std;

int main()
{
    
    
	istringstream iss;
	ostringstream oss;
	stringstream ss;
	string str;

	//istringstream 读入按照空格分开处理
	iss.str("12 3 5 8 # 9 12");
	while(iss>>str)
		cout<<str<<" "; //分别输出12 3 5 8 # 9 12 最后结尾(iss>>str)= 0;
	//ostringstream 输出格式化处理
	oss<<"hello"<<" ";
	oss<<"world"<<endl;
	cout<<oss.str();//输出hello world
	//进制转换
	oss<<hex;
	oss<<16;//以十六进制读入数字16 
	cout<<oss.str()<<endl;//输出10,字符串 
	oss.clear();
	
	//stringstream相当于综合了前面的,而且进制转换更加方便。可以参考https://editor.csdn.net/md/?articleId=104184779

	return 0;
}

2.2 getline

geline的是<string>库中的,原型是

istream& getline(istream &in, string &line, char delim);
其中in是一个输入流,比如cin,将一整行的输入督导line中保存,delim是结束符,默认为'\n'
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>

using namespace std;
int t[20];
void print_f(int a)
{
    
    
	cout<<"print_f t[1]="<<t[1]<<endl;
}
int main()
{
    
    
	istringstream iss;
	ostringstream oss;
	stringstream ss;
	string str;
	getline(cin, str);//输入1 2 3 \n 4 5 6
	cout<<str<<endl;//输出1 2 3 \n 4 5 6
	ss.str(str);
	while(ss>>str)
		cout<<str<<endl;//输出1 2 3 \n 4 5 6
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_39117858/article/details/104613027
今日推荐