给出参数反转字符串

时间:2016-03-27 18:30:14

标签: c string function

我想编写一个函数void reverse_string(char * s),它将作为参数赋予它的以null结尾的C字符串的内容反转。

所以我用它来反转没有参数的内容。但我想知道如何从命令行实现参数。

printf("Floats (a,b) and quotient (c) are : %f,%f,%f \n", a,b,c);

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

这样做:

int main ( int argc, char **argv ) {
     char str [256];
     if(argc > 1)
       strcpy(str, argv[1]);
     else
       printf("no cmd given\n");
     ...
     return 0;
}

但是,您的代码在发布时不应该编译......以下是开始的内容:

gsamaras@gsamaras:~$ gcc -Wall px.c 
px.c: In function ‘main’:
px.c:8:5: warning: implicit declaration of function ‘strcpy_s’ [-Wimplicit-function-declaration]
     strcpy_s(str, "Hello World");
     ^
px.c:9:5: warning: format not a string literal and no format arguments [-Wformat-security]
     printf(str);
     ^
px.c: In function ‘reverse_String’:
px.c:19:14: error: ‘str’ undeclared (first use in this function)
     j=strlen(str)-1;
              ^
px.c:19:14: note: each undeclared identifier is reported only once for each function it appears in

答案 1 :(得分:1)

void reverse_String(char* string);

int main(int argc, char *argv[])
{
    char string[1024];

    if (argc > 1 && strlen(argv[1]) < 1024) {
        strcpy(string, argv[1]);
        printf("%s\n", string);
        reverse_String(string);
        printf("%s\n", string);
    } else {
        // appropriate error message to stderr and then:
        return 1;
    }

    return 0;
}

void reverse_String(char *string)
{
    // implement reversal but don't print it, leave that to main()
}