c - 输入由空格分隔的 int 并将它们传递给 int 数组

标签 c arrays input

我正在尝试用 C 语言编写一个程序,其中用户输入由空格分隔的定义数量的整数(在本例中为 5 个整数)。然后,输入存储在 int 数组中,因此最后可以存储在 char 数组中。

作为程序在要求输入时如何工作的示例:

Input: 20 5 63 4 127

程序的输出应该是:

Output: 20 5 63 4 127

这是我到目前为止所写的,但我不知道如何将输入转换为 int 数组。请注意,我事先知道输入的长度(在本例中,如上所述,为 5 个整数)。

// Input: 20 5 63 4 127


// Ask for user input.

// Store the input in this int array.
int input_int_array[5];

unsigned char char_array[5];

for(int i=0;i<5;i++)
{
    char_array[i]=input_int_array[i];

    printf("%d ", char_array[i]);
}

// Should print: 20 5 63 4 127

最佳答案

您可能需要使用 scanf() 将用户输入作为整数读取到 int 数组中:

#include <stdio.h>

int main() {
    int input_int_array[5];

    // Ask for user input.
    printf("input 5 numbers: ");
    for (int i = 0; i < 5; i++) {
        // Store the input into the array.
        if (scanf("%d", &input_int_array[i]) != 1)
            return 1;
    }

    // Output the contents of the array:
    for (int i = 0; i < 5; i++) {
        printf("%d ", input_int_array[i]);
    }
    printf("\n");
    return 0;
}

关于c - 输入由空格分隔的 int 并将它们传递给 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54714937/

相关文章:

组合公式 "n!/((n-k)!*k!)"不起作用

C 指针,段错误

c - 如何将数组传递给外部函数?

c - 使用 malloc 和不使用 malloc 创建结构体的区别

c - 由于简单错误,lex 文件未编译

c# - 数组可以容纳的最大大小是多少?

c# - Java等同于private static double[,][] _temp = null;的C#数组声明;

C getopt 多个值

image - 如何使用&lt;input&gt;、<image>和canvas从本地文件系统预览一张大图

c++ - 如何在事件窗口之外进行C++输入?