string與int和char之間的型別轉換問題
阿新 • • 發佈:2019-02-11
**string字串轉化為int**
①:
#include<stdlib.h>
string a;
cin >> a;//1111
int n1 = atoi(a.c_str());//n1=1111;
②:
#include <sstream>
stringstream stream;
string result="10000";
int n=0;
stream<<result;
stream>>n;//n等於10000
// stream.clear(); //在進行多次轉換前,必須清除stream
**int轉string字串**
①:
int res=1111;
string test = to_string(res);//將數字轉化為string
②:
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::stringstream stream;
std::string result;
int i = 1000;
stream << i; //將int輸入流
stream >> result; //從stream中抽取前面插入的int值
std::cout << result << std::endl; // print the string "1000"
}
**int轉char陣列**
①:
//itoa貌似已經被遺棄,做法不安全,oj平臺無法通過,vc,code不可以,vs可以
#include<iostream>
#include<string>
#include<algorithm>
#include<stdlib.h>
using namespace std;
int main()
{
char str[32];
int num = 88;
itoa(num, str, 10);//10為10進位制
cout << str;
}
②:
int n = 10000;
char s[10];
sprintf(s,"%d", n);// s中的內容為“10000”,,%d寫錯就會報錯
cout << s;
③:
#include <sstream>
#include <iostream>
int main()
{
std::stringstream stream;
char result[8] ;
stream << 8888; //向stream中插入8888
stream >> result; //抽取stream中的值到result
std::cout << result << std::endl; // 螢幕顯示 "8888"
}