简体   繁体   English

c fgets 重复最后一个字符

[英]c fgets duplicates last character

I am trying to read integer values from stdin.我正在尝试从标准输入读取整数值。 I have a inner while loop that detects integer series so that I can parse ints with multiple characters.我有一个检测整数系列的内部 while 循环,以便我可以解析具有多个字符的整数。 I strtok the buffer with newline delimiters because input can have integers over multiple lines.我用换行符分隔缓冲区,因为输入可以在多行上包含整数。

My code to handle this is:我处理这个的代码是:

while (fgets(buf, BUF_SIZE, stdin)) {
    strtok(buf, "\n");
    for(int i = 0; buf[i] != '\0'; i++) {
        size_t j = 0;
        if(isdigit(buf[i])) {
            while(isdigit(buf[i+(int)j])) {
                j++;
            }
            char *new_str = malloc(j*sizeof(char));
            size_t k =0;
            while(k < j) {
                new_str[k] = buf[i+(int)k];
                k++;
            }
            printf("%s\n", new_str);
            free(new_str);
        }
    }
}

The input could be: 1 9 10 10 11输入可以是:1 9 10 10 11

The output should be:输出应该是:

1
9 
10 
10 
11

The output I get is:我得到的输出是:

1
9
10
0
10
0
11
1

So every last character of input with n>1 gets read twice by the buffer some way.因此,缓冲区以某种方式读取 n>1 输入的每个最后一个字符两次。

I am unsure how this is possible but can't figure it out.我不确定这怎么可能,但无法弄清楚。

This happens because you grow j over the input string but you forget to grow i together with j .发生这种情况是因为您在输入字符串上增加了j但您忘记了将ij一起增加。 So you grow j and after you print it, you will grow i by 1 from the last value, and that i+1 will fall inside the input string that was already printed...所以你增加j并且在你打印它之后,你将从最后一个值增加i 1,并且i+1将落在已经打印的输入字符串内......

The solution is to reinitialize i so:解决方案是重新初始化 i :

        if(isdigit(buf[i])) {
          .....
          free(new_str);
          i = i+j;
        }

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

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