字符串转证书是在工程上经常应用到,在交互界面读取的数据大多数是字符串数据,那么都需要转成整型。
代码思路:
1、输入一个可以带有正负号的整数样子的字符串,例如:12345、-6789等
2、判断是否有符号,并且利用每次读取数字*10,相加的办法,把它恢复为一个完整的整型。
代码如下:
#include <string>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <stdexcept>
using namespace std;
int stringToInt( const string &s )
{
if( s == "-" )
{
throw runtime_error( "invalid parameter" );
}
auto first = s.cbegin();
bool isNegative = ( *first == '-' );
if( isNegative )
{
++first;
}
int value = 0;
for( ; first != s.cend(); ++first )
{
if( isdigit( *first ) )
{
value = value * 10 + ( *first - '0' );
}
else
{
throw runtime_error( "invalid parameter" );
}
}
return isNegative ? -value : value;
}
int main()
{
string s1 = "64";
string s2 = "32";
int result = stringToInt(s1) - stringToInt(s2);
cout << result << endl;
system("pause");
return 0;
}