将数字字符串存储为整数数组

时间:2019-06-14 17:00:25

标签: c arrays c-strings strtol

我正在用C编写一个有用户输入的程序。该输入是一个字符串,整数值之间用空格分隔。数字(第一个数字除外)必须存储在整数数组中。第一个数字表示必须存储多少个数字(即数组的大小)。

在C语言中最简单的方法是什么?这是一个示例:

input--> "5 76 35 95 14 20"

array--> {76, 35, 95, 14, 20}

我一直在搜索,但是找不到我的问题的解决方案。此刻,我试图将输入的值存储在char数组中,并且当有空格时,我使用atoi()将此字符串转换为整数,并将其添加到integer数组中。但是它会打印出奇怪的值。这是代码:

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

int main()
{
    char text[10];
    scanf("%s", text);

    int nums[4];
    int indNs = 0;

    char lastNum[10];
    int indLN = 0;

    for(int i = 0; i < 10; i++)
    {
        if(text[i] == ' ')
        {
            nums[indNs] = atoi(lastNum);
            indNs++;

            sprintf(lastNum, "%s", "");
            indLN = 0;
        } else
        {
            lastNum[indLN] = text[i];
            indLN++;
        }
    }

    nums[indNs] = atoi(lastNum);

    for(int i = 0; i < 4; i++)
    {
        printf("%d\n", nums[i]);
    }
}

2 个答案:

答案 0 :(得分:3)

您不能使用scanf来读取空格分隔的输入,因为scanf一旦碰到空白就会停止读取。

scanf("%s", text); //Wrong, always reads only first number.

您可以在循环中将fgetssscanf%n一起使用。

char buf[100];

int *array = NULL;
int numElements = 0;
int numBytes = 0;
if (fgets(buf, sizeof buf, stdin)) {

   char *p = buf;
   if (1 == sscanf(buf, "%d%n", &numElements,&numBytes)){
       p +=numBytes;
       array = malloc(sizeof(int)*numElements);
       for (int i = 0;i<numElements;i++){
         sscanf(p,"%d%n", &array[i],&numBytes);
         p +=numBytes;
         printf("%d,", array[i]);
       }
   }
}
  

%n返回到目前为止已读取的字节数,因此提前buf数   到目前为止已读取的字节数。


如果您不处理strings并直接从stdin中读取,则不需要所有麻烦。

int *array = NULL;
int numElements = 0;


scanf("%d", &numElements);
array = malloc(sizeof(int)*numElements);

for(int i=0;i<numElements;i++)
{
    scanf("%d", &array[i]);
    printf("%d ", array[i]);
}

答案 1 :(得分:2)

在这种情况下,您可以使用例如在标头strtol中声明的标准C函数<stdlib.h>

例如

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

int main( void )
{
    const char *s = "5 76 35 95 14 20";

    char *p = ( char * )s;

    int n = ( int )strtol( p, &p, 10 );

    int *a = malloc( n * sizeof( int ) );

    for ( int i = 0; i < n; i++ )
    {
        a[i] = strtol( p, &p, 10 );
    }

    for ( int i = 0; i < n; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    free( a );
}

程序输出为

76 35 95 14 20

要读取带空格的字符串,应使用标准的C函数fgets

相关问题