C++ 整形和字串之間的轉換
阿新 • • 發佈:2019-02-18
方法一
使用ANSI C 中的sprintf();和sscanf();函式。
格式化符號
- %%打印出%符號不進行轉換。
- %c 整數轉成對應的 ASCII 字元。
- %d 整數轉成十進位。
- %f 倍精確度數字轉成浮點數。
- %o 整數轉成八進位。
- %s 整數轉成字串。
- %x 整數轉成小寫十六進位。
- %X 整數轉成大寫十六進位。
- %n sscanf(str, “%d%n”, &dig, &n),%n表示一共轉換了多少位的字元
sprintf函式原型為 int sprintf(char *str, const char *format, …)。作用是格式化字串
int main(){
char str[256] = { 0 };
int data = 1024;
//將data轉換為字串
sprintf(str,"%d",data);
//獲取data的十六進位制
sprintf(str,"0x%X",data);
//獲取data的八進位制
sprintf(str,"0%o",data);
const char *s1 = "Hello";
const char *s2 = "World";
//連線字串s1和s2
sprintf(str,"%s %s",s1,s2);
cout<<str<<endl;
return 0;
}
- sscanf函式原型為int sscanf(const char *str, const char *format, …)。將引數str的字串根據引數format字串來轉換並格式化資料,轉換後的結果存於對應的引數內
int main(){
char s[15] = "123.432,432";
int n;
double f1;
int f2;
sscanf(s, "%lf,%d%n", &f1, &f2, &n);
cout<<f1<<" "<<f2<<" " <<n;
return 0;
}
輸出為:123.432 432 11, 即一共轉換了11位的字元。
方法二
使用itoa(),atoi();函式原型如下
char *_itoa(
int value,
char *str,
int radix
);
int atoi(
const char *str
);
char *_ltoa(
long value,
char *str,
int radix
);
long atol(
const char *str
);
方法三
使用stringstream類
該方法很簡便, 缺點是處理大量資料轉換速度較慢.C library中的sprintf, sscanf 相對更快
“sstream”庫定義了三種類:istringstream、ostringstream和stringstream,分別用來進行流的輸入、輸出和輸入輸出操作。
1.stringstream::str(); returns a string object with a copy of the current contents of the stream.
2.stringstream::str (const string& s); sets s as the contents of the stream, discarding any previous contents.
3.stringstream清空,stringstream s; s.str(“”);
4.實現任意型別的轉換
template<typename out_type, typename in_value>
out_type convert(const in_value & t){
stringstream stream;
stream << t;//向流中傳值
out_type result;//這裡儲存轉換結果
stream >> result;//向result中寫入值
return result;
}
使用一個stringstream進行多次格式化時,為了安全需要在中間進行清空
#include <iostream>
#include <sstream>
using namespace std;
int test_sstream()
{
stringstream stream;
stream << "12abc";
int n;
stream >> n;//這裡的n將保持未初始化時的隨機值
cout << n << endl;
stream.str("");
//stream.clear();
stream << "def";
string s;
stream >> s;
cout << s << endl;
return 0;
}
int main()
{
test_sstream();
getchar();
return 0;
}