将 STR 转换为 int 的简单方法?C++
easy method for converting str to int? c++
我正在尝试将字符串转换为整数。我记得一位老师说,你必须从中减去48,但我不确定,当我这样做时,我得到17作为A的值,如果我是正确的64。这是我的代码。任何更好的方法将不胜感激。
#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
string str;
getline(cin,str);
cout << str[0] - 48;
getch();
}
仅使用C++设施的简单且类型安全的解决方案是以下方法:
#include <iostream>
#include <sstream>
int fromString(const std::string& s)
{
std::stringstream stream;
stream << s;
int value = 0;
stream >> value;
if(stream.fail()) // if the conversion fails, the failbit will be set
{ // this is a recoverable error, because the stream
// is not in an unusable state at this point
// handle faulty conversion somehow
// - print a message
// - throw an exception
// - etc ...
}
return value;
}
int main (int argc, char ** argv)
{
std::cout << fromString ("123") << std::endl; // C++03 (and earlier I think)
std::cout << std::stoi("123") << std::endl; // C++ 11
return 0;
}
注意:在fromString()
中,您可能应该检查字符串的所有字符是否实际上构成了有效的整数值。例如,GH1234
或其他东西不会,并且在调用 operator>>
后值将保持 0 。
编辑:刚刚记住,检查转换是否成功的一种简单方法是检查流的failbit
。我相应地更新了答案。
A
不是数字,那么如何将其转换为整数呢?您的代码已经工作。例如,输入 5
,您将看到5
作为输出。当然,这没有任何区别,因为您只是打印该值。但是你可以存储在一个int
变量中:
int num = str[0] - 48;
顺便说一句,通常使用'0'
而不是48(48是0
的ASCII码)。所以你可以写str[0] - '0'
.
有一个atoi
函数可以将字符串转换为 int,但我猜你想在没有库函数的情况下这样做。
我能给你的最好的提示是看一下 ascii 表并记住:
int c = '6';
printf("%d", c);
将打印 ascii 值"6"。
cstdlib 中有一个名为 atoi
的函数,它做的非常简单:http://www.cplusplus.com/reference/cstdlib/atoi/
int number = atoi(str.c_str()); // .c_str() is used because atoi is a C function and needs a C string
这些函数的工作方式如下:
int sum = 0;
foreach(character; string) {
sum *= 10; // since we're going left to right, if you do this step by step, you'll see we read the ten's place first...
if(character < '0' || character > '9')
return 0; // invalid character, signal error somehow
sum += character - '0'; // individual character to string, works because the ascii vales for 0-9 are consecutive
}
如果你给出"23",它就会变成 0 * 10
= 0。 0 + '2' - '0' = 2。下一个循环迭代:2 * 10 = 20。 20 + '3' - '0' = 23
做!
相关文章:
- 一种在C++中读取TXT配置文件的简单方法
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- CPU 瓶颈;处理具有许多非静态对象的 3D 场景渲染的简单方法
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 将时间戳打印到流的最简单方法
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- C++ 将静态方法转换为简单方法
- 将一系列数字映射到 CPP 中的值的简单方法
- 引用基类模板的成员变量的简单方法
- 学习数据结构和算法的简单方法
- boost::variant - 对变体应用算术的最简单方法
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 在C++中将算术类型转换为 std::array 的最简单方法<uint8_t>
- 使用新运算符C++创建多维数组的简单方法
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- OpenSSL模块化最大数据类型大小的简单方法
- 获取当前按键的简单方法
- 多个 if-else 测试的更简单方法
- 为具有多个参数的函数创建 SWIG 类型图的更简单方法?