首页 > 解决方案 > 不使用 atoi 将 char* 字符串转换为 int

问题描述

我是 C++ 的初学者,我想要一种将 char 字符串 (char * str1) 转换为整数的简单方法。我可以用 atoi 做到这一点,但我读过这个功能是“魔鬼”,不应该使用。我不想使用 C++ std:string 有很多原因,所以我的字符串必须是 char* 格式。你有什么建议吗?

提前致谢

标签: c++stringcharatoi

解决方案


作为替代方案,仍然是 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';
}

推荐阅读