【问题标题】:Input ints separated by whitespace and pass them to an int array输入以空格分隔的整数并将它们传递给整数数组
【发布时间】:2019-07-09 22:16:27
【问题描述】:

我正在尝试用 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

【问题讨论】:

  • 这是一个非常广泛的问题。我建议您阅读有关 C 输入的教程。
  • 为什么输入 5 会产生输出 50?这只是一个错字吗?
  • @TimRandall 这是一个错字,我的错。

标签: c arrays input


【解决方案1】:

您可能需要使用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;
}

【讨论】:

    猜你喜欢
    • 2013-01-16
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多