[英]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.
该列表以流结束 (^Z) 或非数字输入终止。
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.或:
1,2 3,4 5,6 7,8
并能够计算它们的统计属性。
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.
请参阅下面的示例。
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.它返回一个结果,但只返回一个固定的数组长度,并给我一堆-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.或者将它们分配给两个不同的数组(x[],y[]),x 代表逗号左边的数字,y 代表右边的数字。
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.嗨,您可以在字符数组的一行中获取整个输入,然后在数组上循环以正确拆分 char 数组以将其转换为整数数组。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.