首页 > 解决方案 > 如何通过 C 中的给定输入创建和打印字符串数组?

问题描述

我刚开始学习 C,但在获取输入以及如何使用它们方面存在一些问题。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int test_case;
    scanf("%d\n",&test_case);
    char arr[test_case][test_case];

    //here, I tried to place values into array
    for (int i = 0; i < test_case; i++) {
        scanf("%s\n",&arr[i]);
    }

    //and print
    for (int j = 0; j < test_case; j++)
        printf("Case #%d %s\n", j+1, arr[j]);

    return 0;
}

如您所见,在这段代码中,首先,我获取了 test_case 值,并使用该大小创建了一个数组 (arr)。但放置并没有按照我想要的方式进行。这就是结果。

3 ->test_case
123 -> 1st element
789 -> 2nd
456 -> 3rd
results
Case #1 123789456
Case #2 789456
Case #3 456

Process returned 0 (0x0)   execution time : 10.155 s
Press any key to continue.

案例 #1 应该是 123,案例 #2 = 789,但我做不到。问题是我该怎么做?

标签: arrayscstringinputscanf

解决方案


我真的不知道你的代码有什么问题。除了你的 scanf 中不需要 '\n'

scanf("%d",test_case);

虽然在这里你走一个简单的方法:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int test_case;
    scanf("%d",&test_case);
    char **arr;
    arr= malloc(test_case*sizeof(char));

    //here, I tried to place values into array
    for (int i = 0; i < test_case; i++) {
        arr[i]=malloc(test_case*sizeof(char));
        scanf("%s",arr[i]);
    }
    //and print
    for (int j = 0; j < test_case; j++)
        printf("Case #%d %s\n", j+1, arr[j]);

    return 0;
}

希望我有帮助!

祝你有美好的一天!


推荐阅读