【问题标题】:How to take a char * containing the string "$Rx", where 'x' is a number, and store the x to a an integer?如何获取包含字符串“$Rx”的char *,其中'x'是一个数字,并将x存储为一个整数?
【发布时间】:2017-11-29 21:41:56
【问题描述】:

所以我有一个文本文件,我读入一个值并将其存储到一个 char * 中。这个变量总是有一个数字,代表我希望稍后在代码中使用的寄存器,作为第三个字符(即 $R0 或 $R1 等)。我想存储到一个名为 register_index1 的预初始化 int 中。作为参考,从下面的 strtok 读取的值是 $R1。

我尝试使用:

    input_E_human = strtok(NULL, " ,");
    register_index1 = atoi(input_E_human[2]);

但这使我的程序出错并且无法编译,所以我在网上看到你可以这样做:

    input_E_human = strtok(NULL, " ,");
    register_index1 = input_E_human[2];

但这也不起作用。它可以编译,但如果我这样做:

    printf("%d",register_index);

它打印出数字 49,而不是 1。这(显然)在我的代码中稍后会导致意外行为。任何帮助将不胜感激...

【问题讨论】:

  • 这些值是否总是具有相同的长度 (3)?
  • 或许sscanf(input_E_human, "$R%d", &register_index);

标签: c char int


【解决方案1】:

如果它总是第三个字符并且总是一个字符长,你可以简单地从中减去’0’,得到一个数字。 C标准要求数字是连续的,所以这有效。

register_index1 = input_E_human[2] - ‘0’;

【讨论】:

    【解决方案2】:

    input_E_human[2]input_E_human 中的第三个字符。但是atoi 需要一个指向字符序列的指针,或者换句话说,是包含整数的字符串中第一个字符的地址。那将是&input_E_human[2],也可以写成input_E_human + 2

    你选择哪一个取决于你喜欢的风格(我通常选择第一个,但没有硬性规定),但理解它们为什么相同对于理解 C 至关重要。

    【讨论】:

      【解决方案3】:

      如果您不关心长度是否为3,则一种方法是这样的:

      #include <stdio.h>
      #include <ctype.h>
      
      int ret ( const char *src );
      
      int main(void){
          char ptr[] = "$R3";
          int number = ret( ptr );
      
          if ( number < 0 ){
              printf("There was no number Found!\n");
              /* do something here */
          }else{
              printf("Number = %d\n", number);
          }
      }
      
      int ret ( const char *src ){
          int i = 0;
          int tmp = 0;
          int count = 0;
      
          while(src[i] != '\0' ){
              if( isdigit (src[i]) ){ // if( ( src[i] >= '0' ) && ( src[i] <= '9' )  ){}
                  tmp = src[i] - '0';
                  count++;
              }
              i++;
          }
      
          if ( count == 0 ){
              return -1;
          }else{
              return tmp;
          }
      }
      

      输出:

      Number = 3
      

      就像您注意到的那样,您需要做的就是用'0' 减去ptr[i]

      当然,如果有多个数字,我相信您现在可以根据需要调整代码。但是如果你只关心最后一个数字,那么这段代码就可以了。

      即使您有这样的字符串"$5H4j9R3",它仍然会打印3,这是最后一个数字。

      【讨论】:

        猜你喜欢
        • 2020-01-05
        • 2020-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多