argv []中的int中断并只打印int

时间:2016-10-29 19:48:04

标签: c argv

所以我知道这是基础知识,但我不知道在哪里可以找到正确的答案。问题是我需要运行一个带有参数-s的程序,然后跟一个数字告诉它输入跳过多少个字符,比如我们这样做(我在bash中运行它):

echo "hue" |./prog -s 2

然后应该只打印e,而shell会给我

  

2someone @某处:

此时我被困了好几个小时无法理解,请帮助。

int main(int argc, char *argv[]) {
    char s;
    char input[8196];
    int i = 0;
    /* above initialized are variables needed for the root of the program to work */
    int s_num = 0; /* "-s" or skip */
    int cnt_1; /* lvl1 counter */
    /* Getting input */
    while ((s = getchar()) != EOF) {
        input[i] = s;
        printf("%d\n", i);
        i++;
    }

    /* If calling w/o arguments, the only thing that works */
    if (argc == 1) {
        //do stuff
    }

    /* Argument Check */  
    if (argc > 1) {
        printf("1\n");
        for (cnt_1 = 0; cnt_1 < argc; cnt_1++) {
            printf("2\n");

            if (strcmp(argv[cnt_1], "-s") == 1) {
                printf("3.1\n");
                int pom = cnt_1 + 1;
                int bqs = 0;
                for (int i = 0; argv[pom][i] != '\0'; ++i) {
                    bqs *= 10; bqs += argv[pom][i] - '0';
                }
                s_num = bqs;
            }
            ...

3 个答案:

答案 0 :(得分:2)

第一个参数,即argv[0]包含可执行文件的名称。 因此,开始在数组argv[1]的第二个元素处搜索参数并从那里开始。

for (cnt_1 = 1; cnt_1 < argc; cnt_1++)
//           ^  change 0 to 1 here

如果您在评论中说不允许使用<string.h>,那么也许您可以对char char进行argv[]比较每个字符串中包含的字符串通过循环时... if((argv[cnt_1][0] == '-') && (argv[cnt_1][1] == 's'))//argument "-s" found, handle it { ... 的字符串:

context "Validators:" do
  it "does not allow a User without a username" do
    expect(User.new(:username=> "")).to_not be_valid
  end

  it "does not allow a Profile with a null first and last name" do
    expect(Profile.new(:first_name=>nil, :last_name=>nil, :gender=>"male")).to_not be_valid
  end
end

答案 1 :(得分:2)

您的代码中存在多个问题:

  • char s;应为int s;,否则循环while ((s = getchar()) != EOF)无法正常运行。默认情况下,根据char类型是已签名还是未签名,它会在\377个字符上提前停止,或者无法完全匹配EOF

  • 您不会在i之前检查sizeof(input)是否小于input[i] = s;。任何足够长的输入文件都会导致缓冲区溢出。

  • 在检查此参数是否与atoi(argv[cnt_1 + 1])不同之后,您应该使用NULL来转换size参数。

  • 如果您不能使用strcmp()检查参数值或atoi()转换数字,请使用指针变量并单独检查字符:

    char *p = argv[cnt_1];
    if (p[0] == '-' && p[1] == 's' && p[2] == '\0') {
        int skip = 0;
        char *s = argv[cnt_1 + 1];
        if (s != NULL) {
            while (*s >= '0' && *s <= '9') {
                skip = skip * 10 + *s++ - '0';
            }
        }
    }
    
  • 最后但并非最不重要:如果您可以使用strcmp(),则不应对其返回值进行假设,除非它可以是负数,0或正数。您应该将strcmp(argv[cnt_1], "-s") == 1更改为strcmp(argv[cnt_1], "-s") == 0以检查字符串是否相同。它strcmp()是你自己的实现,当你在评论中提示时,它会非常容易出错,给它不同的语义。写一个strequal()函数返回一个布尔值并只测试if (strequal(argv[cnt_1], "-s"))

答案 2 :(得分:1)

if (strcmp(argv[cnt_1], "-s") == 1)

那应该是0. strcmp在等于​​0时返回0。

  

0 1 2 3 1 2 2   3.1 2

这就是我从输出中得到的结果,它可以预期,因为最后一个是-s的值。你确定你的strcmp工作正常吗?