如何从输入中读取两行数字到2个数组,C语言?不知道数量?在 C

问题描述 投票:0回答:4

例如输入为:

12 23 32 41 45
22 11 43

行以

'\n'
,

结尾

我想将 nums 保存到

a[]
b[]
;

a[] = {12, 23, 32, 41, 45}
b[] = {22, 11, 43}

重点是我不知道每行有多少个数字。

如果我知道 line1

n
数字和 line2
m
数字,我将使用“for 循环”,毫无疑问。

就像,

for(int i = 0; i < n; i++) scanf("%d", a+i);
for(int i = 0; i < m; i++) scanf("%d", b+i);

但是,我不知道 n 和 m,该怎么办,伙计们?

c scanf
4个回答
1
投票

如果您想继续使用 scanf 方法,我建议使用否定的 scanset

%[^]
格式说明符。

scanf("%[^\n]", pointerToCharArray)

这应该读取任意数量的字符,最多为但不包括指定的字符(在我们的例子中,是换行符)。如果您想放弃换行符,请按如下方式读取:

scanf("%[^\n]\n", pointerToCharArray)

下面可以找到参考页面的链接。否定的扫描集说明符包含在列表中:

http://www.cplusplus.com/reference/cstdio/scanf/

从这一点来看,使用 strtok() 将 scanf 的输出标记为数字数组是一件简单的事情。如果您不熟悉 strtok,下面提供了另一个参考链接:

http://www.cplusplus.com/reference/cstring/strtok/

我希望这有帮助!


0
投票

让我们使用非标准

getline
,一个常见的库扩展。 @Abbott整个行读入分配的内存中。

如果需要数组并且其大小在运行时确定,请使用C99中可用的可变长度数组,也可以选择在C11中使用。

创建一个函数来计数并可能保存数字。使用

strto...()
函数进行稳健的解析。

size_t count_longs(char *line, long *dest) {
  size_t count = 0;
  char *s = line;
  for (;;) {
    char *endptr;
    long num = strtol(s, &endptr, 10);
    if (s == endptr) {
      break;  /// no conversion
    }
    s = endptr;
    if (dest) {
      dest[count] = num;
    }
    count++;
  }
  return count;
} 

示例代码片段

  char *line = NULL;
  size_t len = 0;
  ssize_t nread = getline(&line, &len, stdin);  // read the whole line
  if (nread != -1) {
    // successful read

    long a[count_longs(line, NULL)];  // determine array size and use a 
    count_longs(line, a);             // 2nd pass: assign array elements. 

    nread = getline(&line, &len, stdin);
    if (nread != -1) {
      // successful read

      long b[count_longs(line, NULL)];
      count_longs(line, b);

      // Do something with a and b
    }
  }
  free(line);
  len = 0;

0
投票

下面的代码可能符合OP的要求。 该解决方案读取未指定数量的整数值并将它们存储在

arr
中。要中断循环/结束输入,只需输入一个非整数值。可以进一步指定它来搜索特定的输入等。

int c = 0;
int *arr = NULL;
int *extArr = NULL;
int i = 0;
for (i = 0; scanf("%d", &c) == 1; i++)
{
    extArr = (int*)realloc(arr, (i+1) * sizeof(int)); 
    arr = extArr;
    arr[i] = c; 

}
free(arr);

但是,我个人会混合使用我提供的解决方案和armitus答案(如果我不能使用

getline
或类似的),因为为每个int值重新分配内存对我来说似乎是多余的。

编辑由于对我提供的代码以及如何最好地使用它来满足OP的问题存在一些疑问。 codenippet 应该展示如何创建自己的 scanf 式函数,用于一次读取一个完整数组的未指定数量的整数输入(在这种情况下,必须省略

free()
,直到完成数组(显然) ).


0
投票

我认为这可以适合你的情况:

int a[100], i = 0; char c;
do
{
    scanf("%ld", a+i);
    i++;
} while ((c = getchar()) == ' ');

这很有效,因为它不仅在遇到换行符时停止将数字读入数组

a
,而且在遇到其他非空格和非数字字符时也停止将数字读入数组。

您也可以在从其他流读取时使其工作,只需将

scanf
替换为
fscanf
,将
getchar
替换为
fgetc

© www.soinside.com 2019 - 2024. All rights reserved.