在C中扫描没有空格的n个数字

时间:2013-12-10 09:55:34

标签: c scanf

假设n个数字在一行中输入而没有任何空格,条件是这些数字的条件是它们介于1和10之间。

假设n为6,那么输入就像“239435” 那么如果我有一个数组,我在其中存储这些数字,那么我应该得到

    array[0]=2
    array[1]=3
    array[2]=9
    array[3]=4  
    array[4]=3

我可以使用array[0]=(input/10^n)然后使用下一个数字来获得上述结果 但有更简单的方法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用字符串来获取输入,然后检查每个位置并将它们取出并存储在数组中。您需要明确检查每个位置的数值,因为您接受输入为字符串。对于以字符串形式输入的整数,没有保证输入是纯数字,如果不是,那么事情就会变得疯狂。

检查此代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        char ipstring[64];
        int arr[64];
        int count, len = 0;
        printf("Enter the numbersi[not more than 64 numbers]\n");
        scanf("%s", ipstring);
        len = strlen(ipstring);
        for (count = 0; count < len ; count++)
        {
                if (('0'<= ipstring[count]) && (ipstring[count] <= '9'))
                {
                        arr[count] = ipstring[count] - '0';

                }
                else
                {
                        printf("Invalid input detectde in position %d of %s\n", count+1, ipstring );
                        exit(-1);
                }
        }
        //display
        for (count = 0; count < len ; count++)
        {
                printf("arr[%d] = %d\n", count, arr[count]);
        }
        return 0;
}

答案 1 :(得分:2)

只需为每个数字减去0的ASCII码,即可得到它的值。

 char *s =  "239435"
 int l = strlen(s);
 int *array = malloc(sizeof(int)*l);
 int i;
 for(i = 0; i < l; i++)
      array[i] = s[i]-'0';

<强>更新

假设0不是有效输入,只允许1-10之间的数字:

 char *s =  "239435"
 int l = strlen(s);
 int *array = malloc(sizeof(int)*l);
 int i = 0;
 while(*s != 0)
 {
      if(!isdigit(*s))
      {
           // error, the user entered something else
      }

      int v = array[i] = *s -'0';

      // If the digit is '0' it should have been '10' and the previous number 
      // has to be adjusted, as it would be '1'. The '0' characater is skipped.
      if(v == 0)
      {
           if(i == 0)
           {
               // Error, first digit was '0'
           }


           // Check if an input was something like '23407'
           if(array[i-1] != 1)
           {
               // Error, invalid number
           }
           array[i-1] = 10;
      }
      else
          array[i] = v;

     s++;
 }

答案 2 :(得分:2)

E.g。

int a[6];
printf(">");
scanf("%1d%1d%1d%1d%1d%1d", a,a+1,a+2,a+3,a+4,a+5);
printf("%d,%d,%d,%d,%d,%d\n", a[0],a[1],a[2],a[3],a[4],a[5]);

结果:

>239435
2,3,9,4,3,5