簡體   English   中英

讀取12個數字組成的數組,每個數字之間都有空格-C編程

[英]Reading in an array of 12 numbers with spaces in between each number - C programming

我是一名新的C編程專業的學生,​​遇到了當前正在使用的代碼的麻煩。 我需要詢問用戶12個條形碼,每個值之間都有空格。 另外,稍后在代碼中,我將需要引用數組中的每個單獨的值。 例如,如果我的數組是x[12] ,則需要使用x[1]x[2]和所有其他值來計算奇數和,偶數和等。以下是我要讀取的第一個函數條形碼使用for循環。 此功能的腳本的任何幫助將有所幫助。

#include <stdio.h>
#define ARRAY_SIZE 12

int fill_array() {
    int x[ARRAY_SIZE], i;
    printf("Enter a bar code to check. Separate digits with a space >\n");

    for(i=0; i<ARRAY_SIZE; i++){
        scanf("% d", &x);
    }
    return x;
}

您應該傳遞數組以將其作為參數讀取,並在其中存儲讀取的內容。

另請注意, % dscanf()的無效格式說明符。

#include <stdio.h>
#define ARRAY_SIZE 12

/* return 1 if suceeded, 0 if failed */
int fill_array(int* x) {
    int i;
    printf("Enter a bar code to check. Separate digits with a space >\n");

    for(i=0; i<ARRAY_SIZE; i++){
        if(scanf("%d", &x[i]) != 1) return 0;
    }
    return 1;
}

int main(void) {
    int bar_code[ARRAY_SIZE];
    int i;
    if(fill_array(bar_code)) {
        for(i=0; i<ARRAY_SIZE; i++) printf("%d,", bar_code[i]);
        putchar('\n');
    } else {
        puts("failed to read");
    }
    return 0;
}

或者,您可以在函數中分配一個數組並返回其地址。

#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 12

/* return address of array if succeeded, NULL if failed */
int* fill_array(void) {
    int *x, i;
    x = malloc(sizeof(int) * ARRAY_SIZE);
    if (x == NULL) {
        perror("malloc");
        return NULL;
    }
    printf("Enter a bar code to check. Separate digits with a space >\n");

    for(i=0; i<ARRAY_SIZE; i++){
        if(scanf("%d", &x[i]) != 1) {
            free(x);
            return NULL;
        }
    }
    return x;
}

int main(void) {
    int *bar_code;
    int i;
    if((bar_code = fill_array()) != NULL) {
        for(i=0; i<ARRAY_SIZE; i++) printf("%d,", bar_code[i]);
        putchar('\n');
        free(bar_code);
    } else {
        puts("failed to read");
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM