[英]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.