c++ - 不使用 atoi 将 char* 字符串转换为 int
问题描述
我是 C++ 的初学者,我想要一种将 char 字符串 (char * str1) 转换为整数的简单方法。我可以用 atoi 做到这一点,但我读过这个功能是“魔鬼”,不应该使用。我不想使用 C++ std:string 有很多原因,所以我的字符串必须是 char* 格式。你有什么建议吗?
提前致谢
解决方案
作为替代方案,仍然是 C 风格,使用sscanf
:
/* sscanf example */
#include <stdio.h>
int main ()
{
char sentence []="Rudolph is 12 years old";
char str [20];
int i;
sscanf (sentence,"%s %*s %d",str,&i);
printf ("%s -> %d\n",str,i);
return 0;
}
[编辑] 正如@Killzone Kid在评论中所报道的,有一个标准版本。
#include <iostream>
#include <clocale>
#include <cstdio>
int main()
{
int i, j;
float x, y;
char str1[10], str2[4];
wchar_t warr[2];
std::setlocale(LC_ALL, "en_US.utf8");
char input[] = u8"25 54.32E-1 Thompson 56789 0123 56ß水";
// parse as follows:
// %d: an integer
// %f: a floating-point value
// %9s: a string of at most 9 non-whitespace characters
// %2d: two-digit integer (digits 5 and 6)
// %f: a floating-point value (digits 7, 8, 9)
// %*d an integer which isn't stored anywhere
// ' ': all consecutive whitespace
// %3[0-9]: a string of at most 3 digits (digits 5 and 6)
// %2lc: two wide characters, using multibyte to wide conversion
int ret = std::sscanf(input, "%d%f%9s%2d%f%*d %3[0-9]%2lc",
&i, &x, str1, &j, &y, str2, warr);
std::cout << "Converted " << ret << " fields:\n"
<< "i = " << i << "\nx = " << x << '\n'
<< "str1 = " << str1 << "\nj = " << j << '\n'
<< "y = " << y << "\nstr2 = " << str2 << '\n'
<< std::hex << "warr[0] = U+" << warr[0]
<< " warr[1] = U+" << warr[1] << '\n';
}
推荐阅读
- python - 根据可用的时间段/日历将人们分组在一起的算法
- excel - 您如何编码 VBA 以使用具有对象单元格边界的求解器?
- reactjs - 如何根据 React JS 中另一个数组的值过滤数组
- generics - 如何缩短长的where子句?
- r - R studio 仅对 2 组中的 1 组进行配对 t 检验
- typescript - React Native 0.64.0 不会更新 ios 中的包
- python - 请解决此错误,ModuleNotFoundError: No module named 'binance.websockets'
- c# - 您可以将参数传递到您的 TestFixture 中吗?
- c# - 参数在c#中使用位图无效
- javascript - Amazon Web Service:获取今天日期的 API