简体   繁体   English

C编程命令行参数

[英]C Programming Command Line Argument

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

int main(int args, char *argv[]) {
    int i = 0;
    for (i = 0; i < args; i++)
        printf("\n%s", argv[i]);
    return 0;
}

As of now this program prints out whatever is written on the command line. 到目前为止,该程序将打印出在命令行上写入的内容。 How would I make it do this in reverse? 我将如何做到这一点呢? For example, if I input "dog" it should say "god". 例如,如果我输入“ dog”,则应该说“ god”。

Try the following code: 尝试以下代码:

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

int main(int argc, char *argv[]) {
    int i = 0;
    for (i = 1; i < argc; i++)
    {
        char *tmp = argv[i];
        int len = strlen(argv[i]);
        for(int j = len-1; j > -1; --j)
            printf("%c",tmp[j]);
        printf("\n");
    }
    return 0;
}

I'd break this down into two smaller tasks. 我将其分解为两个较小的任务。

  1. Write a helper function that, given a string, prints it out in reverse order. 编写一个辅助函数,给定一个字符串,以相反的顺序将其打印出来。 To do so, you could use a loop that starts at the end of the string and prints each character one after the other, moving in reverse across the array as you go. 为此,您可以使用一个循环,该循环从字符串的末尾开始,一个接一个地打印每个字符,然后在数组中反向移动。

  2. Call that helper function in main inside the loop to print each string in the argv array. 在循环内部的main调用该辅助函数,以打印argv数组中的每个字符串。

Since this looks like a homework assignment, I'll leave it at this. 由于这看起来像是一项家庭作业,因此我将其留在这里。 If you're having trouble with step (1), then you may need to review how to do string processing a bit before jumping into this problem. 如果您在执行步骤(1)时遇到问题,则可能需要回顾一下如何进行字符串处理,然后再跳入此问题。

IDEOne Link IDEOne链接

int main(int argc, char *argv[]) {
    for (int i = 0; i < argc; ++i)
    {
        for(char* c = &argv[i][strlen(argv[i])-1]; c >= argv[i]; putchar(*c--)) ;
        putchar(' ');
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM