【问题标题】:Store string with numbers as an integer array将带有数字的字符串存储为整数数组
【发布时间】:2019-06-14 17:00:25
【问题描述】:

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

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

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

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

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

#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]);
    }
}

【问题讨论】:

  • fgets then sscanf in loop 是最简单的。
  • 喜欢int array[5]; int unused; sscanf(input, "%d %d %d %d %d %d", &amp;unused, &amp;array[0], &amp;array[1], &amp;array[2], &amp;array[3], &amp;array[4])?
  • @Kamilcuk 10 3 6 4 6 4 5 5 4 5 4 怎么样
  • @Carcigenicate 我上传了帖子。

标签: c arrays c-strings strtol


【解决方案1】:

您不能使用scanf 读取空格分隔的输入,因为scanf 将在遇到空格后停止读取。

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

您可以在循环中使用fgets 后跟sscanf%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]);
}

【讨论】:

  • 不需要将整行读入缓冲区,只需使用scanf("%d", &amp;foo)分别读取每个整数即可
  • 哦,还有malloc(),但没有free()
【解决方案2】:

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

例如

#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

【讨论】:

    猜你喜欢
    • 2015-02-08
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多