在C++裡,要達到字串與數字之間的轉換,可利用STL的方式...在STL 中有一個型別叫做stringstream , 此種型別可以利用來作字串與數字的轉換
如果要使用stringstream 的話必須宣告 #include <sstream>
程式解說如下:
#include <iostream>
#include <cstring>
#include <sstream>
using namespace std;
int main()
{
string str1 = "12345";
string str2 = "123.45";
int num1;
double num2;
stringstream ss1,ss2; //宣告2個stringstream 變數
ss1<<str1; //從字串變數str1 "輸出" 到字串串流ss1中
ss2<<str2; //從字串變數str2 "輸出" 到字串串流ss2中
ss1>>num1; //從字串串流ss1 "輸入" 到正整數變數num1中
ss2>>num2; //從字串串流ss2 "輸入" 到浮點數變數num2中
cout<<"INT = "<<num1<<endl;
cout<<"DOUBLE = "<<num2<<endl;
return 0;
}
以上範例是示範如何將單一數字字串 轉換成數字型別儲存
但stringstream 也可以處理多數字的字串陣列,例如從檔案讀入二維陣列元素...
範例如下
#include <iostream>
#include <cstring>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
fstream file_read;
file_read.open("data.txt",ios::in);
//string buffer;
char *buffer = new char[50];
int i=0,j=0;
int tmp[2][5]; //字串轉int 之暫存變數
/*
*一次讀入檔案一整行並儲存到buffer字串
*buffer型別必須使用char * 不可使用string 類別
*參考 C++ reference
*istream& getline (char* s, streamsize n );
*istream& getline (char* s, streamsize n, char delim );
*/
while(file_read.getline(buffer,50))
{
stringstream ss3(buffer); //將buffer字串輸出到字串串流物件ss3
while(ss3>>tmp[i][j]) //將字串串流中的每個元素依序 "輸入" 到tmp
{
j++;
}
i++;
j=0;
}
cout<<"ARRAY!\n";
for(int m=0; m<2 ;m++)
{
for(int n=0 ; n<5;n++)
{
cout<<tmp[m][n]<<"\t";
}
cout<<endl;
}
return 0;
}
data.txt內容
1 -3 5 -7 9
-2 4 -6 8 -10
程式輸出內容
kimi@kimi-ubuntu:~$ ./test2.out
ARRAY!
1 -3 5 -7 9
-2 4 -6 8 -10