【问题标题】:String to Int without atoi/isdigit没有 atoi/isdigit 的字符串到 Int
【发布时间】:2016-02-11 05:50:31
【问题描述】:

如何在不使用atoiatolisdigit 之类的东西的情况下将字符串转换为数组?

假设我有一个const char *str 和一个int *converted_val 作为参数。

这是我所拥有的:

const char *c;
    for(c = str; (*c != '\0') && isdigit(*c); ++c){
                    *converted_value = *converted_value*10 + *c - '0';
    }
    return true;

但再一次,如果没有 isdigit,我将无法做到这一点。而且我不确定如何处理大字符串(例如:“10000000000000000”)

【问题讨论】:

标签: c type-conversion


【解决方案1】:
int yetAnotherAtoi(char *str)
{
 int res = 0; // Initialize result

 // Iterate through all characters of input string and
 // update result
 for (int i = 0; str[i] != '\0'; ++i) {
     if (str[i]> '9' || str[i]<'0')
         return -1; # or other error...
     res = res*10 + str[i] - '0';
 }

 // return result.
 return res;
}

【讨论】:

    【解决方案2】:

    *c &gt;= '0' &amp;&amp; *c &lt;= '9'替换isdigit(*c)

    const char *c;
    ....
    for( c = str; *c != '\0' && *c >= '0' && *c <= '9'; ++c) {
        *converted_value = (*c - '0') + *converted_value*10;
    }
    return true;
    

    请注意,ASCII 符号 '0''9' 是按升序排列的。

    您仅限于 converted_value 的整数数据类型的范围。

    【讨论】:

    • 是的!完美的!知道我将如何处理大型案件吗? *str = "10000000000"?
    • 其实09的连续性是由标准来保证的,不管是不是ASCII。对于az不是也是如此。
    • @MikeHenke 您仅限于 converted_value 的 integratl 数据类型的范围。
    • 您应该根据 INT_MAX(和 INT_MIN)检查转换中的溢出并处理错误情况。或者将您的类型更改为 long(或系统上的 64 位类型,可能是 int64_t)。然后,您需要检查 64 位类型的限制并处理错误。
    【解决方案3】:

    变化:

    int *converted_val
    

    long int *converted_val
    

    为更大的值留出更多空间。您也可以考虑添加代码来检查输入字符串是否会溢出您的输出变量。

    【讨论】:

      【解决方案4】:

      如果您想在 Visual Studio 中不使用函数将字符串转换为整数,您可以执行以下代码:

      #include "stdafx.h"
      #include<iostream>
      #include<string>
      #include<conio.h>
      using namespace std;
      
      int main()
      {
      
          std::string str ;
          getline(cin, str);
          int a = 0;
          for (int i = 0  ; i<str.length(); i++) {
              a = (int)(str[i] - 48) + a * 10;
          }
          cout << a;
      
          _getch();
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2010-12-02
        • 1970-01-01
        • 1970-01-01
        • 2020-08-24
        • 2013-05-25
        • 2012-10-13
        • 2023-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多