简体   繁体   中英

C - How to read input separated by commans and whitespaces

I have a question on how to read input and assigning it to an array (or even two arrays).

I have a project where I have to:

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

Your program must handle any length of list. The list will be input (or piped) from the console, or read from a file. The list is terminated with end-of-stream (^Z) or non-numeric input.

So basically, the program has to read:

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

or: 1,2 3,4 5,6 7,8 and be able to calculate their statistic properties.

I know how to do the calculations and create the functions etc. My question is, how to implement the parts: "any length of the list" and "list of real number pairs". See sample below.

sample output

What I tried so far:

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

which returns a the result, but only to a fixed array length and gives me a bunch of -858993460 -858993460.

For now, I just want to know how to read the input properly and assign them to one Array, so I can read the odd and even index and calculate their mean and whatever respectively...

or assign them to two different arrays (x[], y[]), x for the digit on the left of the comma, y on the right.

Hi you can get the entire input in a single line in a character array and then loop on the array to correctly split the char array to convert it into integer array. Below is the code you can try :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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