麻烦argv和char

时间:2013-07-27 19:17:27

标签: c char argv

两个小时后,我正在尝试修改我的程序,给它参数(argv)而不是char。

所以,这是我目前的代码:

int i;
 char ret[81];
    *ret = 1;
    for (i = 0; i < argc; i++)
    { 
            ret[0] = '\0';
          strcat(ret,argv[i]);
    }

这段代码将所有args连接成一个char,printf返回与旧的char参数完全相同的结果,但不能在我的代码中工作:

char test[] = "9...7....2...9..53.6..124..84...1.9.5.....8...31..4.....37..68..9..5.74147.......";
        solve(test); //working
        solve(ret); //not working

我的应用就是这样推出的: ./a.out“9 ... 7 ....”“2 ... 9..53”“.6..124 ..”“84 ...... 1.9。” “5 ..... 8 ..”“。31..4 ......”“。。37..68。” “.9..5.741”“47 .......”

Soooo,如果有人理解我的问题,我可能需要一些帮助:D

1 个答案:

答案 0 :(得分:0)

示例代码:

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

void solve(char *data){
    static const char *result = "9...7....2...9..53.6..124..84...1.9.5.....8...31..4.....37..68..9..5.74147.......";
    if(strcmp(result, data) == 0)
        printf("working\n");
    else
        printf("not working\n");
}

int main(int argc,  char *argv[]){
    int i, total_length = 0;

    for(i = 1; i < argc; ++i){
        total_length += strlen(argv[i]);
    }

    char ret[total_length + 1];

    ret[0] = '\0';
    for(i = 1; i < argc; ++i){
        strcat(ret, argv[i]);
    }
    char test[] = "9...7...."
                  "2...9..53"
                  ".6..124.."
                  "84...1.9."
                  "5.....8.."
                  ".31..4..."
                  "..37..68."
                  ".9..5.741"
                  "47.......";
    solve(test);
    solve(ret);

    return 0;
}