我想将一个字符串转换为int,我不是指ASCII码。
为了快速回顾,我们将一个方程作为字符串传递。我们要把它分解,正确地格式化并解出线性方程。说到这里,我不能把一个字符串转换成int型。
我知道字符串的格式是(-5)或(25)等,所以它肯定是int型。但是我们如何从字符串中提取它呢?
我想到的一种方法是在字符串中运行一个for/while循环,检查一个数字,提取后面的所有数字,然后看看是否有前导'-',如果有,将int乘以-1。
对于这样一个小问题来说,这似乎有点过于复杂了。什么好主意吗?
一行版本:long n = strtol(s.c c_str(), NULL, base);.
(s为字符串,base为int,如2,8,10,16)
你可以参考这个链接了解更多关于strtol的细节。
核心思想是使用sttol函数,该函数包含在cstdlib中。
由于strtol只处理char数组,我们需要将字符串转换为char数组。你可以参考这个链接。
一个例子:
#include <iostream>
#include <string> // string type
#include <bitset> // bitset type used in the output
int main(){
s = "1111000001011010";
long t = strtol(s.c_str(), NULL, 2); // 2 is the base which parse the string
cout << s << endl;
cout << t << endl;
cout << hex << t << endl;
cout << bitset<16> (t) << endl;
return 0;
}
它将输出:
1111000001011010
61530
f05a
1111000001011010
诚然,我的解决方案不适用于负整数,但它将从包含整数的输入文本中提取所有正整数。它使用numeric_only locale:
int main() {
int num;
std::cin.imbue(std::locale(std::locale(), new numeric_only()));
while ( std::cin >> num)
std::cout << num << std::endl;
return 0;
}
输入文本:
the format (-5) or (25) etc... some text.. and then.. 7987...78hjh.hhjg9878
输出整数:
5
25
7987
78
9878
类numeric_only定义为:
struct numeric_only: std::ctype<char>
{
numeric_only(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
static std::vector<std::ctype_base::mask>
rc(std::ctype<char>::table_size,std::ctype_base::space);
std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
return &rc[0];
}
};
完整在线演示:http://ideone.com/dRWSj
要将字符串表示形式转换为整数值,可以使用std::stringstream。
如果转换的值超出整数数据类型的范围,则返回INT_MIN或INT_MAX。
此外,如果字符串值不能表示为有效的int数据类型,则返回0。
#include
#include
#include
int main() {
std::string x = "50";
int y;
std::istringstream(x) >> y;
std::cout << y << '\n';
return 0;
}
输出:
50
根据上面的输出,我们可以看到它从字符串数转换为整数数。
来源和更多的字符串int c++
为了更详尽(正如评论中要求的那样),我使用std::from_chars添加了c++ 17给出的解决方案。
std::string str = "10";
int number;
std::from_chars(str.data(), str.data()+str.size(), number);
如果您想检查转换是否成功:
std::string str = "10";
int number;
auto [ptr, ec] = std::from_chars(str.data(), str.data()+str.size(), number);
assert(ec == std::errc{});
// ptr points to chars after read number
此外,要比较所有这些解决方案的性能,请参阅以下快速工作台链接:https://quick-bench.com/q/GBzK53Gc-YSWpEA9XskSZLU963Y
(std::from_chars是最快的std::istringstream是最慢的)