c - 如何在 (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);
}
解决方案
第一个参数是 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]);
}
}
推荐阅读
- javascript - 使用基于选定的一个 ActionResult 从不同表中获取结果
- r - 如何在 r 中更改树形图的颜色
- python-3.x - 使用 Subprocess 来避免长时间运行的任务断开 discord.py bot?
- matlab - MATLAB 想要将显式欧拉算法转换为一阶 ODE 系统的隐式欧拉算法
- typescript - 导出默认的RouteConfig数组
- bash - 自动化 post-“git move”,制作历史日志
- node.js - 节点进程内存使用量超过 --max_old_space_size
- python - 从 python 类调用函数期间的语法混淆
- android - ConstraintLayout 彼此之间的中心视图
- android - Android Robotium solo - 如何访问 IFRAME 中包含的 WebElements?