2015-10-27 242 views
0

当前我正在尝试取一个二进制字符串,比如说100101010,并将其拆分为三个组,因此10010110。以下是我迄今为止所写的内容,由于某些原因,它仅适用于打印第一个组,然后在此之后没有任何内容。将字符串拆分为数组C

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

int main(){ 

    int i; 
    char *line = NULL; 

    free(line); 
    scanf("%ms", &line); 

    printf("%d\n", strlen(line)); 

    for(i=0; i < strlen(line); ++i) { 

     if (i % 3 == 0){ 
      sprintf(line, "%c%c%c", line[i],line[i+1],line[i+2]); 
      printf(line); 
     } 

    } 

} 
+0

你为什么要释放一个NULL指针? – John3136

+0

这并不是一件可怕的事情。如果您释放空指针,则实际上不会发生任何事 – Chirality

+1

的确,我知道它是无害的,但是在免费说'line = NULL'之前的那一行,所以它没有意义。为什么包括无意义的代码 - 它使真正的问题难以发现......顺便说一句 - 你实际上并没有在最终释放线路,所以你有一个空闲的地方你不需要它,并且在你做的地方缺少一个; - ) – John3136

回答

2

sprintf(line, "%c%c%c", line[i],line[i+1],line[i+2]);你3个字符写入line,所以你覆盖原始字符串与第一组3。这意味着下一次通过循环i(4)> strlen(line)(3)等循环停止。

尝试:

/* Since 'line' and it's contents doesn't change in the loop we can 
* avoid the overhead of strlen() calls by doing it once and saving the 
* result. 
*/ 
int len = strlen(line); 

/* As mentioned in the comments, you could do 
* for(i = 0; i < len; i+=3) and then you don't need the 
* if (i%3) check inside the loop 
*/ 
for(i=0; i < len; ++i) { 
    if (i % 3 == 0){ 
     /* This could be refactored to a loop 
     * or scanf() to a different string but I say scanf is overkill 
     * in this scenario... 
     */ 
     char buffer[4]; 
     buffer[0] = line[i]; 
     buffer[1] = line[i+1]; 
     buffer[2] = line[i+2]; 
     buffer[3] = '\0'; 
     printf("%s\n", buffer); 
     // Or just use puts() since we're not really doing 
     // any formatting. 
    } 
} 
+0

这很好,谢谢!为了澄清,将循环内的字符串组合使得strlen每次更小,这使得它只能运行一次? – Chirality

+0

是的。 'scanf(line ...'改变了行的内容,所以strlen返回了一个不同的值,我将编辑上面的另一个注释 – John3136

+1

为什么不行'for(i = 0; i

0

的strlen(线)重新评估每个经过的循环,你改变了数据线点里面的for循环调用sprintf的。你的sprintf使行成为3个字符的字符串,因此你只能通过i%3为零的循环的一次行程。