读取字符串中的数字序列

Read a sequence of numbers in a String

我必须编写一个程序来接收数字序列,将它们存储在一个 (int) 数组中并以相反的顺序打印。输入由两行组成:第一行包含一个整数,表示整数的数量,第二行包含由空格分隔的整数 space 以倒序打印,如下例:

输入:

4

2 5 45 10

输出:

10 45 5 2

问题是我无法将每个整数存储在数组的不同位置,因为它们仅由空格 space(而不是 [Enter])分隔。我该如何解决这个问题? (对不起英语,这不是我的母语)。

scanf 完成任务:

  int max;
  scanf("%d", &max); 

  for (int i = 0; i < max; i++)
  {
    int number;
    scanf("%d", &number); 
    printf("%d\n", number);
  }

这允许您输入:

3
11 12 13

你会得到这个输出:

11
12
13

将数字存储在数组中并以相反的顺序显示它们作为练习留给 reader。

如果编译器支持可变长度数组,那么你可以编写如下内容

#include <stdio.h>

int main( void ) 
{
    unsigned int n;

    if ( scanf( "%u", &n ) == 1 && n != 0 )
    {
        int a[n];
        unsigned int i = 0;

        while ( i < n && scanf( "%d", &a[i] ) == 1 ) i++;

        while ( i != 0 ) printf( "%d ", a[--i] );
        printf( "\n" );
    }
}    

如果进入

4
2 5 45 10

则程序输出为

10 45 5 2

否则你应该在读取第一个数字后动态分配数组。