c - 读取由 12 个数字组成的数组,每个数字之间有空格 - C 编程

标签 c arrays pointers

我是一名新 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;
}

关于c - 读取由 12 个数字组成的数组,每个数字之间有空格 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35834762/

相关文章:

c++ - 段错误 : Dynamically allocating large integer array

java - groovy 如何使用名称创建数组?

javascript - if 语句的条件应该等于 true 但事实并非如此

c++ - std::cout 不打印到控制台

带有效载荷的 C 双字面值 NaN

c - 为什么这个程序只打印第一个字符?

c++ - 什么类型的指针操作

c - 在不使用数组的情况下将指向字符的指针(在为其分配字符串之后)传递给方法并修改此字符串是否适用,为什么不呢?

c - 如何在 Trinket 上生成/处理监听器?

java - 用于 C++ 实现的 native JNI 静态方法的 Java 运行时错误