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;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章