【问题标题】:Pulling two ints from string in C从C中的字符串中提取两个整数
【发布时间】:2012-10-23 17:52:03
【问题描述】:

说如果我有这样的字符串

char foo[10] = "%r1%r2";

我想取出12 并将它们转换成ints。我该怎么做?

【问题讨论】:

  • 字符串“喜欢”什么? %-字母编号-%-字母编号?只是混杂在一起?

标签: c string parsing


【解决方案1】:
if (sscanf(foo, "%%r%d%%r%d", &i1, &i2) != 2)
    ...format error...

当你为sscanf() 做格式时,我知道%d 是一个十进制整数,但为什么你有%%r

如果您要在源字符串中查找文字 %,则使用 %% 在格式字符串中指定它(在 printf() 中,您在格式字符串中使用 %% 来生成% 在输出中); r 代表它自己。

还有其他方式指定转换,如%*[^0-9]%d%*[^0-9]%d;它使用分配抑制(*)和扫描集([^0-9],任何不是数字的东西)。此信息应可从sscanf() 的手册页获得。

【讨论】:

  • 这有帮助,谢谢,但我有一个问题......当你为 scanf 执行格式时,我知道 %d 是一个十进制整数,但为什么你有 %%r?我不确定你能解释什么?
【解决方案2】:

您可以使用sscanf() 获取结果

【讨论】:

    【解决方案3】:

    考虑到您的字符串确实有两个 '%' 和每个后面的一个数字。 例如:

      char foo[10] = "%123%874";
    

    不要忘记包含 stdlib 库:

       #include <stdlib.h>
    

    以下代码将 123 输入 r1 并将 874 输入 r2。

      for(int i = 1; ; i++)
          if(foo[i] == '%')
          {
              r2 = atoi(&foo[i + 1]); // this line will transform what is after the second '%' into an integer and save it into r2
              foo[i] = 0; // this line will make the place where the second '%' was to be the end of the string now
              break;
          }
      r1 = atoi(&foo[1]); // this line transforms whatever is after the first character ('%') into an int and save it into r1
    

    【讨论】:

      【解决方案4】:
      int array[MAXLEN];
      int counter = 0; 
      for(int i = 0; i < strlen(foo); i++){
         if(isdigit(foo[i]) && (counter < MAXLEN)){
              array[counter++] = (int)(foo[i]-'0');
         }
      }
      //integers are in array[]. 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-09
        • 2020-07-20
        相关资源
        最近更新 更多