首页 > 解决方案 > 如何在 (int argc, char **argv) 中打印 argv

问题描述

我想知道如何打印 argv 的特定部分。例如

./program hello world
The first 3 letters of the first argument is:
1 = h
2 = e
3 = o
The full argument was: hello

The first 3 letters of the second argument is:
1 = w
2 = o
3 = r
The full argument was: world

这是我的代码,我只是不知道在那个特定的地方放什么

int main(int argc, char **argv) {
    printf("The first 3 letters of the first argument is:\n");
    int i = 0;
    while (i < 3) {
        printf("%d = %c\n", .... I don't know what to put here);
        i++;
    }
    printf("The full word was: %s\n\n", I don't know what to put here);

    printf("The first 3 letters of the second argument is:\n");
    int j = 0;
    while (j < 3) {
        printf("%d = %c\n", j, .... I don't know what to put here);
        j++;
    }
    printf("The full word was: %s\n", I don't know what to put here);
}

标签: carrayschararguments

解决方案


第一个参数是 in argv[1],第二个参数是argv[2],依此类推。要从中打印单个字符,请添加另一个级别的下标。

您还应该在打印参数之前检查是否提供了参数,并且它们有足够的字符可以在循环中打印。

int main(int argc, char **argv) {
    if (argc >= 2) {
        printf("The first 3 letters of the first argument is:\n");
        int i = 0;
        while (i < 3 && argv[1][i]) {
            printf("%d = %c\n", i, argv[1][i]);
            i++;
        }
        printf("The full word was: %s\n\n", argv[1]);
    }

    if (argc >= 3) {
        printf("The first 3 letters of the second argument is:\n");
        int j = 0;
        while (j < 3 && argv[2][j]) {
            printf("%d = %c\n", j, argv[2][j]);
            j++;
        }
        printf("The full word was: %s\n", argv[2]);
    }
}

推荐阅读