上一篇列举了把int转成string的方法,这篇列举把string如何转成int,以及除了调用已有的API,如何自己写方法来进行转换。
#include "stdafx.h"
#include <iostream>
using namespace std;
#define CALL(namespace, method) \
{\
cout << "Calling " #namespace"::" #method ":"<< endl;\
method;\
}
#pragma region Convertstring to
namespace SC
{
string s = "199";
string sf = "199.9";
int i;
float f;
// C++ 11: stoi
#include <string>
void TestStoi()
{
i = stoi(s);
cout << i << endl;
f = stof(sf);
cout << f << endl;
}
// stringstream
#include <sstream>
void TestSStream()
{
stringstream stream;
stream << s;
stream >> i;
cout << i << endl;
}
// C: atoi
#include <stdlib.h>
void TestAtoi()
{
i = atoi(s.c_str());
cout << i << endl;
f = atof(sf.c_str());
cout << f << endl;
}
// Write custommethod
void TestCustomMethod()
{
const char* temp =s.c_str();
int sign = 1, result = 0;
if (*temp == '+')
temp++;
else if (*temp =='-')
{
temp++;
sign = -1;
}
while (*temp)
{
result = result * 10 +*temp - '0';
temp++;
}
result *= sign;
cout << result << endl;
}
// Boostlexical_cast
#include <boost/lexical_cast.hpp>
void TestBoostLexicalCast()
{
cout << boost::lexical_cast<int>(s)<< endl;
}
// strtol
void TestStrtol()
{
cout << static_cast<int>(strtol(s.c_str(),nullptr, 10))<< endl;
}
// sscanf
void TestSScanf()
{
sscanf_s(s.c_str(), "%d", &i);
cout << i << endl;
}
void TestConvertStringTo()
{
CALL(SC, TestStoi());
CALL(SC, TestSStream());
CALL(SC, TestAtoi());
CALL(SC, TestCustomMethod());
CALL(SC, TestBoostLexicalCast());
CALL(SC, TestStrtol());
CALL(SC, TestSScanf());
}
}
#pragma endregion
#define USE(name)using namespace name
#define TEST(namespace, method) \
{\
USE(namespace);\
method;\
}
int main()
{
TEST(SC, TestConvertStringTo());
return 0;
}