這邊也可以用stringstream來實做
下面是把字串轉成數值
當然反過來也可以把數值轉為字串
簡單的實作了以下code
1.數值轉字串
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char *argv[]) { stringstream Data1,Data2; string str1,str2; int a; float b; cout << "請輸入一個整數:"; getline(cin,str1); cout << "請輸入一個小數:"; getline(cin,str2); Data1 << str1; Data2 << str2; Data1 >> a; Data2 >> b; cout << "輸入的整數為:" << a << endl; cout << "輸入的小數為:" << b << endl; system("PAUSE"); return EXIT_SUCCESS; }
2.字串轉數值
(這邊把數值+5來確認字串是否確實轉換為數值)
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char *argv[]) { stringstream Data; string str; float a; cout << "請輸入字串:"; getline(cin,str); Data << str; Data >> a; cout << "+5後的值:" << a+5 << endl; system("PAUSE"); return EXIT_SUCCESS; }
沒有留言:
張貼留言