string转化成int
来源:互联网 发布:mysql use index 编辑:程序博客网 时间:2024/05/16 15:28
上一篇列举了把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)usingnamespace name
#define TEST(namespace, method) \
{\
USE(namespace);\
method;\
}
int main()
{
TEST(SC, TestConvertStringTo());
return 0;
}
- int转化成string
- string转化成int
- [VC++.NET编程]int转化成String
- String类型转化成Int类型
- int string 等转化
- int转化为string
- String和int转化
- CString/string/int转化
- string转化为int
- string 转化为int,int转化为string
- c++ string 转化为 int
- string和int互相转化
- C# int与string转化
- C# int与string转化
- js int string转化方式
- C# int与string转化
- C++中把int类型变量转化成string类型
- C++中把int类型变量转化成string类型
- Codeforces 903D Almost Difference
- 文章标题
- ROS机器人程序设计(原书第二版)笔记
- Spring Boot 拦截器 请求参数MD5签名校验
- 图解设计模式
- string转化成int
- JavaScript 实用技巧和写法建议
- 每天一道LeetCode-----将链表中满足条件的节点移动到前面
- 系统负载能力浅析
- 515. Find Largest Value in Each Tree Row
- 成为 Linux 终端高手的七种武器
- 亲自动手写一个Python库(一)
- spring整合hibernate的时候使用session的时候报:is not valid without active transaction
- 原生js实现addClass,removeClass,hasClass方法