天天看點

用stringstream讀取資料

思想:

全部讀到一個字元串裡,遇到","就換成空格,然後用這個字元串構造一個stringstream, 用>>讀到數組裡。

stringstream用法

分為istream和ostringstream.

1     std::string name("zeta");
2     int age = 27;
3 
4     ostringstream os;
5     os << "name:"<<name<<""<<"age:"<<age<<endl;
6     cout<<os.str()<<endl;      

輸出:name:zeta age:27

1     std::string name("zeta");
 2     int age = 27;
 3 
 4     ostringstream os;
 5     os << "name:"<<name<<""<<"age:"<<age<<"\n";
 6 
 7     istringstream is(os.str());
 8     std::string tmp;
 9     int age1;
10 
11     // name:zeta
12     is >> tmp;
13     cout<<tmp<<endl;
14 
15     // age:27
16     is >> tmp;
17     cout<<tmp<<endl;      

注釋為輸出結果,注意從stringstream中解析對象的時候,是以空格和Enter鍵為分隔符的。

1     std::string name("12345");
2     int age = 27;
3     stringstream os;
4     os << name;
5     os >> age;
6     // age = 12345
7     cout<<age<<endl;      
1     std::string name("12345");
2     int age = 27;
3     stringstream os;
4     os << age;
5     os >> name;
6     // name:27
7     cout<<name<<endl;      

可以作為将數字和字元串互相轉化的工具。

輸入輸出的頭檔案 <iostream> 

string流的頭檔案 <sstream> 

檔案流的頭檔案   <fstream> 

stringstream的用法

1.利用輸入輸出做資料轉換

stringstream ss_stream;
ss_stream << i;   // 将int輸入流中
ss_stream >> str; // 将ss_stream中的數值輸出到str中

//注意:如果做多次資料轉換;必須調用clear()來設定轉換模式
ss_stream << "456"; 
ss_stream >> i;   // 首先将字元串轉換為int
ss_stream.clear();
ss_stream << true;
ss_stream >> i;   // 然後将bool型轉換為int;假如之前沒有做clear,那麼i會出錯

//運作clear的結果 
i = 456 
i = 1 
//沒有運作clear的結果 
i = 456 
i = 8800090900       

2.支援char*的輸入和輸出

char sz_buf[20];
ss_stream << 8888;
ss_stream >> sz_buf; // 直接将數輸出到sz_buf字元數組中      

3.來存儲可變資料的清單

stringstream ss_stream;
ss_stream << "字元串一" << endl;
ss_stream << "字元串二" << endl;
ss_stream << "字元串三" << endl;
ss_stream << "字元串四" << endl;
ss_stream << "字元串五" << endl;

char buffer[100];
while ( ss_stream.getline(buffer, sizeof(buffer))
{
    printf("msg=%s\n", buffer);
}
ss_stream("");// 釋放字元串流中的資源

// 或者用string來接收
stringstream ss_stream;
string stemp;
while ( getline(ss_stream, stemp) )
{
    task_download(stemp.c_str(), relate.c_str());
}      

繼續閱讀