1. 程式人生 > >C/C++中字串與數值相互轉換

C/C++中字串與數值相互轉換

第一種方法:

數字轉換成字串:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

string num2str(double i)
{
	stringstream ss;
	ss << i;
	return ss.str();
}

int main()
{
	double x = 965.3;
	string s = num2str(x);
	cout << s << endl;
	return 0;
}

字串轉換成數字:
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int str2num(string str)
{
	int num;
	stringstream ss(str);
	ss >> num;
	return num;
}

int main()
{
	string str = "123456";
	int x = str2num(str);
	cout << x << endl;
	return 0;
}

上面方法缺點是處理大量資料轉換速度較慢。

******************************************************************************************************************************

第二種方法:

以下內容來源於C++標準庫

自C++11開始,C++標準庫提供了一些便捷函式,用來將string轉換成數值或者反向轉換,然而請注意,這些轉換隻可用於型別 string 和 wstring ,不適用於u16string和 u32string。


對於上面所有“將string轉換為數值”的函式,以下都適用:

  • 它們會跳出前導的任何空白字元。
  • 它們允許返回“被處理之最末字元”後的第一個字元的索引。
  • 如果轉換無法發生,它們會丟擲std::invalid_argument,如果被轉換值超出返回型別的可表達範圍,它們會丟擲std::out_of_rang。
  • 對於整數,你可以(也可以不)傳遞基數(base)。
對於所有將數值轉換為 string 或 wstring 的函式,val 可以是以下任何型別:int、unsigned int、long、unsigned long、unsigned long long、long long、float、double 或者 long double。 舉個例子,考慮一下程式:
#include <iostream>
#include <sstream>
#include <string>
#include <limits>
#include <exception>

int main()
{
	try {
		//convert to numeric type
		std::cout << std::stoi("  77") << std::endl;
		std::cout << std::stod("  77.7") << std::endl;
		std::cout << std::stoi("-0x77") << std::endl;

		//use index of characters not processed
		std::size_t idx;
		std::cout << std::stoi("  42 is the truth", &idx) << std::endl;
		std::cout << " idx of first unprocessed char: " << idx << std::endl;

		//use bases 16 and 8
		std::cout << std::stoi("  42", nullptr, 16) << std::endl;
		std::cout << std::stoi("789", &idx, 8) << std::endl;
		std::cout << " idx of first unprocessed char: " << idx << std::endl;

		//convert numerix value to string
		long long ll = std::numeric_limits<long long>::max();
		std::string s = std::to_string(ll);//converts maximum long long to string
		std::cout << s << std::endl;

		//try to convert back
		std::cout << std::stoi(s) << std::endl; //throws out_of_range
	}
	catch (const std::exception& e)
	{
		std::cout << e.what() << std::endl;
	}
}

輸出如下:

注意std::stoi("-0x77")會導致0,因為它只解析-0,然後就把x解釋為它所找到的數值終點;std::stol("789",&idx,8)只解析string中第一個字元,因為8在八進位制中不是個有效字元。

相關推薦

C/C++字串數值相互轉換

第一種方法: 數字轉換成字串: #include <iostream> #include <sstream> #include <string> using namespace std; string num2str(double

C語言字串整數的相互轉換

C語言提供了幾個標準庫函式,可以將任意型別(整型、長整型、浮點型等)的數字轉換為字串,下面列舉了各函式的方法及其說明。 # include <stdlib.h> 將數字轉換為字串   ● itoa():將整型值轉換為字串。   ● ltoa():將長整

C語言字串數值型別之間的轉換

c語言的演算法設計中,經常會需要用到字串,而由於c語言中字串並不是一個預設型別,其標準庫stdlib設計了很多函式方便我們處理字串與其他數值型別之間的轉換。首先放上一段展示各函式使用的程式碼,大家也可以copy到自己的機器上執行觀察#include <stdio.h&g

C語言字串數字相互轉換

在C/C++語言中沒有專門的字串變數,通常用字元陣列來存放字串。字串是以“\0”作為結束符。C/C++提供了豐富的字串處理函式,下面列出了幾個最常用的函式。   ● 字串輸出函式puts。   ● 字串輸出函式gets。   ●

C/C++ 字串數字相互轉換

https://www.cnblogs.com/happygirl-zjj/p/4633789.html 一.利用stringstream類 字串到整數 stringstream sstr(str); int x; sstr >> x;(即從sstr中提取資料)

c++字串數字的轉換

字串流類(sstream)用於string的轉換 <sstream>:相關標頭檔案 istringstream:字元輸入流 ostringstream:字元輸出流 使用方法: #inclu

C++stringchar相互轉換

一、string轉char* 1.data()方法 string str = "hello"; const char* p = str.data(); //或char * p=(char*)str.data(); 2.c_str()方法 stri

(各種)C/C++ 字串數字相互轉換

一、C標準庫atoi, itoa(C++11標準) 字串和int互轉 1. itoa函式 char *itoa(int value, char *string, int radix); value: 待轉化的整數。 radix: 是基數的意思,即先將value轉化

C++ 字串數字的轉換

數字轉字串1.sprintf_s函式 //sprintf函式 int a = 100; float b = 10.30; char str[10]; sprintf_s(str,"%d",a

c++intchar相互轉換

一、ASCII表 瞭解int與char相互轉換之前,先讓我們看一下ASCII碼錶。 其中數字字元對應的位置為:48 - 57。 二、char轉int char轉int之前,先將運算式中的每個字元都轉換成ASCII碼值,再進行計算。 以下程式碼為例,其中i3的結

C#.net開發 ListDataTable相互轉換

inf columns serve property eat 這一 異常 bject 屬性 1、DataTable轉List集合 /// <summary> /// DataTable轉化為List集合 ///

c++標準庫數字字元相互轉換

1.字串轉數字 使用C++11引入的C++庫函式將string轉換為數值型別,相應的庫函式申明於標頭檔案<string>中。 名稱    原型    說明 stoi    int stoi

C++整型\字串\陣列的相互轉換

總體思路: 1. 直接使用itoa轉換 2. 用sprinf(buf, "%d", 234") 3. 用ostringstream sout; sout<<234; sout.str()就

javaintbyte相互轉換

基礎內容簡介      在做轉換之前先要明確幾個簡單的概念。首先本文是以java為語言,以int為例子。 long資料型別在原理上是一致的。      1  int 在java中是32位, byte是8位。      2  原碼,反碼,補碼簡介        

javascript json字串物件相互轉換

 在實際專案中,經常遇到字元格式的問題,記下來以便日後方便檢視。用到兩個函式:JSON.stringify() 和 JSON.parse()。  使用ajax向後臺請求資料,後臺給前端返回資料,明明後端指令碼寫的是json函式處理後的json格式,但是前端接收資料時,卻時而是

python實現字串二進位制相互轉換

#Convert a string to a binary def encode(Target_string): return ’ ‘.join([bin(ord©).replace(‘0b’, ‘’) for c in Target_string]) #Convert binary to

java陣列List相互轉換的方法

1.List轉換成為陣列。(這裡的List是實體是ArrayList)   呼叫ArrayList的toArray方法。   toArray   public <T> T[] toArray(T[] a)返回一個按照正確的順序包含此列表中所有元素的陣列;返回陣列

AndroidDrawableBitmap相互轉換的方法

1..Bitmap轉Drawable Drawable drawable =new BitmapDrawable(bmp); 2.Drawable轉Bitmap Resources res=getResources(); Bitmap bmp=BitmapFa

【整理】C/C++字串整數之間的相互轉換

最近刷題過程中總是碰到這個知識點,因此做個總結記錄一下。 一、用C標準IO庫中的sprintf()和sscanf()轉換  sprintf()函式原型: #include <stdio.h> int sprintf(char *str,const char

OC字串C語言字串之間的相互轉換

1、C轉OC字串 const char *cString = "This is a C string"; // 動態方法 NSString *ocString1 = [[NSString alloc] initWithUTF8String:cString]; NSString *ocString2 = [