c++ string 轉int,float


  std::string為library type,而int、double為built-in type,兩者無法利用(int)或(double)的方式互轉,

法1:
使用C的atoi()與atof()。

先利用c_str()轉成C string,再用atoi()與atof()。

int atoi ( const char * str ); //c++ 頭文件cstdlib c stdlib.h
Convert string to integer

Parses the C string str interpreting its content as an integral number, which is returned as an int value.

 

法2:

利用stringstream

這里使用functon template的方式將std::string轉int、std::string轉double。

#include <iostream>
10#include <sstream>
11#include <string>
12
13template <class T> 
14void convertFromString(T &, const std::string &);
15
16int main() {
17  std::string s("123");
18
19  // Convert std::string to int
20  int i = 0;
21  convertFromString(i,s);
22  std::cout << i << std::endl;
23
24  // Convert std::string to double
25  double d = 0;
26  convertFromString(d,s); 
27  std::cout << d << std::endl;
28
29  return 0;
30}
31
32template <class T> 
33void convertFromString(T &value, const std::string &s) {
34  std::stringstream ss(s);
35  ss >> value;
36}

http://www.cnblogs.com/oomusou/archive/2006/10/10/525647.html

深入:

http://sealbird.iteye.com/blog/866701

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM