3

So I decided to learn C and using learn c the hard way. At any rate I tried editing one of the examples and the output isn't what I expected it would be. I call the program from the command line as e14 asd which "should" print: 'e' == 101 'a' == 97 's' == 115 'd' == 100

But, it doesn't print the 'd' line at all. The code I have is:

#include <stdio.h>
#include <ctype.h>

void print_letters(int argc, char *arg[])
{
    int i = 0;
    int j = 0;
    for(j = 0; j < argc; j++) {
        for(i = 0; arg[i] != '\0'; i++) {

            char ch = arg[j][i];
            printf("j is %d and i is %d\n", j, i);

            if(isalpha(ch) || isblank(ch)) {
                printf("'%c' == %d \n", ch, ch);
            }
        }
        printf("\n");
    }
}


int main(int argc, char *argv[])
{
    print_letters(argc, argv);
    return 0;
}

I'm assuming the problem has to do with the argv part but after looking around, I still have no idea what exactly is causing the 'd' not appear.

If someone could explain it to me it's be appreciated.

Thanks!

4

2 回答 2

10
for(i = 0; arg[i] != '\0'; i++) {

应该

for(i = 0; arg[j][i] != '\0'; i++) {
//            ^^^

循环退出条件应该遍历单个命令行参数的字符,但实际上是遍历参数。

于 2013-07-10T07:17:10.620 回答
0

在使用命令行参数之前,您应该知道它argc计算参数的数量,并且argv是一个用于存储参数的二维数组。在这种情况下,例如,如果 exe 文件名是main.exe并且您main.exe asd在命令行中键入,则参数的值应该是argc == 2argv[0] == 'main.exe'argv[1] == 'asd'. 有关命令行参数用法的更多详细信息,请参阅解析 C 命令行参数

于 2013-07-10T07:32:25.597 回答