gpt4 book ai didi

c - 如何在 (int argc, char **argv) 中 printf argv

转载 作者:行者123 更新时间:2023-11-30 18:46:24 26 4
gpt4 key购买 nike

我想知道如何打印 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);
}

最佳答案

第一个参数位于 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]);
}
}

关于c - 如何在 (int argc, char **argv) 中 printf argv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777587/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com