在C中按char打印命令行参数char [英] Printing command line arguments char by char in C

查看:148
本文介绍了在C中按char打印命令行参数char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的:

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

int main(int argc, char **argv)
{

    while(*argv++ != 0)
    {
            printf("Argument!\n");
            printf("%s %d\n",*argv,(int)strlen(*argv));
            int i = 0;

            while(*argv[i])
            {
                    printf("char!\n");
                    printf("%c\n",*argv[i]);
                    i++;
            }

            printf("End of for loop\n");
    }

    return 0;
}

当我运行./a.out测试时,输出为:

When I run ./a.out test, the output is:

Argument!
test 4
char!
t
Segmentation Fault

我一直盯着这个看了几个小时.为什么我的程序不按字符打印每个命令行参数?

I've been staring at this for a few hours. Why won't my program print each command line argument character by character?

我是C语言和数组指针对偶的新手,所以如果这是问题,我不会感到惊讶.感谢您的帮助!

I'm new to C, and the array-pointer duality, so I wouldn't be surprised if that were the problem. Any help is appreciated!

推荐答案

第一版

您想要的是使用argc:

First version

What you want is use argc:

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

int main(int argc, char **argv)
{
    int i = 0;
    int j = 0;
    for (i = 0; i < argc; i ++)
    {
    j = 0;      
    while(argv[i][j] != '\0')
       printf("Argument %d letter %d : %c\n", i,j,argv[i][j++]);   
    }
    return 0;
}

根据需要,输出实际上是逐字母的:

The output is actually letter by letter as you needed:

$./a.out hello world
Argument 0 letter 1 : .
Argument 0 letter 2 : /
Argument 0 letter 3 : a
Argument 0 letter 4 : .
Argument 0 letter 5 : o
Argument 0 letter 6 : u
Argument 0 letter 7 : t
Argument 1 letter 1 : h
Argument 1 letter 2 : e
Argument 1 letter 3 : l
Argument 1 letter 4 : l
Argument 1 letter 5 : o
Argument 2 letter 1 : w
Argument 2 letter 2 : o
Argument 2 letter 3 : r
Argument 2 letter 4 : l
Argument 2 letter 5 : d

第二版:

您可以将指针表示法用于j,但不能用于i,因为您不知道每个参数的字母数.当然,这可以通过使用strlen来实现,它会在引擎盖下通过字符串进行迭代以对字母进行计数,这不是您想要执行的操作.如果您可以通过参数在一次迭代中做到这一点,为什么要在两次迭代中做到呢?

Second version:

You can use the pointer notation for j but not for i since you don't know the letter count of each argument. It could of course be achieved by using strlen which would lead under the hood to an iteration through the string to count the letter, which is not what you want to do. If you can do it in one iteration through the argument why do it in two?

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

int main(int argc, char **argv)
{
    int i = 0;int j = 0;
    while(i < argc)
    {
    j=0;
    while(*(argv[i]+j) != '\0')
    {
            printf("Argument %d letter %d : %c\n", i,j,*(argv[i]+(j)));
            j++;
    } 
     i++;
    }
    return 0;

}

这篇关于在C中按char打印命令行参数char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆