我想知道如何打印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);
}
发布于 2018-08-10 09:16:12
第一个参数是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]);
}
}
发布于 2018-08-11 01:55:10
argv中的第一个元素是程序的名称,其余元素指向参数。通过遍历参数argv1到argvn,可以找到每个参数的前三个字符,同时为每个参数打印所需的字符。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
printf("Program: %s\n", argv[0]);
if (argc > 2)
{
int i = 1;
for ( ; i < argc ; i++)
{
if (!argv[i][2])
{
fprintf(stderr,"Length of argument \"%s\" is less than 3\n", argv[i]);
return(EXIT_FAILURE);
}
else
printf("The first 3 letters of argument %d is:\n", i);
int j = 0;
while(j < 3)
{
printf("Index %d in agument \"%s\" is %c\n", j, argv[i], argv[i][j]);
j++;
}
}
}
else
fprintf(stderr,"Missing arguments\n");
return(EXIT_FAILURE);
return(EXIT_SUCCESS);
}
发布于 2018-08-10 09:26:59
代码:
#include <stdio.h>
#include <string.h>
const int num_chars = 3;
int main(int argc, char **argv) {
if(argc == 1) return 1;
if(num_chars <= 0) return 1;
for(int i=1; i<argc; i++)
{
if(num_chars > strlen(argv[i])) return 1;
printf("The first %d chars of %s is:\n", num_chars, argv[i]);
for(int j=0; j<num_chars; j++)
{
printf("%d = %c\n", j, argv[i][j]);
}
printf("\n");
}
return 0;
}
有效案例:
$ ./test hello world
The first 3 chars of hello is:
0 = h
1 = e
2 = l
The first 3 chars of world is:
0 = w
1 = o
2 = r
大小写无效:
$ ./test hel wo
The first 3 chars of hel is:
0 = h
1 = e
2 = l
https://stackoverflow.com/questions/51777587
复制相似问题