string(char*)与基本数据类型的转换
<span style="font-size:18px;">#include<iostream>
#include<string>
#include<sstream>
using namespace std;
#include<stdlib.h>
#include<string.h>
#define ISDIGIT(ch) ((ch)>='0'||'9'<=(ch))
int StringToInt(const string& Str);
template<class T>
string TransString(const T& val);
//模拟手算过程 能写全不容易
int TransStrinToint(const string& Str);
int StringToInt(const string& Str)
{
//使用的时候直接使用 不用写函数
/*
遇到非法字符便停止转换 我们如果写成模板形式 那么想转double也可以
*/
stringstream ss;
ss << Str;
int Ret=0;
ss >> Ret;
return Ret;
}
template<class T>
string TransString(const T& val)
{
//这比c语言的sprintf itoa atoi 好用的多
stringstream ss;
ss << val;
string Str = ss.str();
return Str;
}
//经典手写代码题 不过能写完整不容易
int TransStrinToint(const string& Str)
{
/*
1 将返回值先设为long long型 返回时与int判断大小
2 使用数组(不符合题目意思)
3 判断越界 但是一定要注意 在越界前判断
*/
/*
static const int MAX_INT = (int)((unsigned)~0 >> 1);
static const int MIN_INT = -(int)((unsigned)~0 >> 1) - 1;
*/
const unsigned int MAX =INT_MAX;
const unsigned int MIN =-INT_MIN;
int num = 0;
if (Str.empty())
{
//如果为空
return num;
}
int i = 0, cur = 0;
int sign = 1;
if ('+'==Str[0])
{
sign = 1;
++i;
}
else if ('-' == Str[0])
{
sign = -1;
++i;
}
while (i<(int)Str.length()&&(ISDIGIT(Str[i])||' '==Str[i]))
{
if(' ' == Str[i])
{
}
else
{
cur = Str[i] - '0';
//在这里判断是否溢出
if ((1 == sign)&&((num>MAX/10)||num==MAX/10&&(cur>MAX%10)))
{
return MAX;
}
else if ((-1 == sign) && ((num > MIN / 10) || num == MIN / 10 && (cur > MIN % 10)))
{
return MIN;
}
else
{
num = num * 10 + cur;
}
}
++i;
}
return num*sign;
}
int main(void)
{
string Str1 = "--123s";
cout << "StringToInt by stringstream: " << StringToInt(Str1) << endl;
double d1 = -0.1234;
cout << "TransString by stringstream:" << TransString(d1) << endl;
string Str2 = "-123231651531315615616516545";//溢出了
string Str3 = TransString<int>(INT_MAX-1);//2147483647
Str3 = "-2147483649";
cout << "TransStrinToint by calculate:" << TransStrinToint(Str3) << endl;
puts("------------------------------------------");
const char* p = "- 123";
cout << "atoi:" << atoi(p) << endl;
int num = -123;
char buffer[200] = "";
_itoa_s(num, buffer, 10);
printf("itoa %s\n", buffer);
char s[] = "computer", c = 'l';
int i = 35, j;
float fp = 1.7320534f;
//没有常用C语言写程序 函数功能很强大
/*
int sprintf_s(
char *buffer,
size_t sizeOfBuffer,
const char *format [,
argument] ...
);
*/
j = sprintf_s(buffer, 200, " String: %s\n", s);
j += sprintf_s(buffer + j, 200 - j, " Character: %c\n", c);
j += sprintf_s(buffer + j, 200 - j, " Integer: %d\n", i);
j += sprintf_s(buffer + j, 200 - j, " Real: %f\n", fp);
printf_s("Output:\n%s\ncharacter count = %d\n", buffer, j);
double d2 = -123.456;
return 0;
}</span>