繁体   English   中英

C - 如何读取由逗号和空格分隔的输入

[英]C - How to read input separated by commans and whitespaces

我有一个关于如何读取输入并将其分配给数组(甚至两个数组)的问题。

我有一个项目,我必须:

Create a C console application to compile the following statistics on a list of real number pairs:
•   minimum value;
•   maximum value;
•   median value;
•   arithmetic mean;
•   mean absolute deviation – (mean, median, mode)
•   variance (of a discrete random variable);
•   standard deviation (of a finite population);
•   mode (including multi-modal lists).
•   least squares regression line
•   outliers

您的程序必须处理任何长度的列表。 该列表将从控制台输入(或通过管道传输),或从文件中读取。 该列表以流结束 (^Z) 或非数字输入终止。

所以基本上,程序必须阅读:

1,2
2,23
3,45
5,34

或: 1,2 3,4 5,6 7,8并能够计算它们的统计属性。

我知道如何进行计算和创建函数等。我的问题是,如何实现这些部分:“列表的任意长度”和“实数对列表”。 请参阅下面的示例。

样本输出

到目前为止我尝试了什么:

#include <stdio.h>

int main()
{    
    int a[100];
    int b[100];
    int n = 100;
    
    for (int i = 0; i < n; i++) {
        scanf_s("%d,", &a[i]);
    }

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

    return 0;
}

它返回一个结果,但只返回一个固定的数组长度,并给我一堆-858993460 -858993460。

现在,我只想知道如何正确读取输入并将它们分配给一个数组,这样我就可以读取奇数和偶数索引并分别计算它们的平均值和任何东西......

或者将它们分配给两个不同的数组(x[],y[]),x 代表逗号左边的数字,y 代表右边的数字。

嗨,您可以在字符数组的一行中获取整个输入,然后在数组上循环以正确拆分 char 数组以将其转换为整数数组。 以下是您可以尝试的代码:

#include <stdio.h>
#include <stdlib.h>
int main( void )
{
  char *src = (char*)malloc(sizeof(char) * 500);
  fgets(src, 500, stdin);
  int arr[500];
  int index = 0;
  int n;
  while ( sscanf ( src, "%d%n", &arr[index], &n ) == 1 ) {
  //while ( sscanf ( src, "%d,%n", &arr[index], &n ) == 1 ) {  ////Use this for values separated by commas
    printf("%d\n", arr[index]);
    index++;
    src += n;
  }
  return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM