Can some one explain why the token will always losing words instead of got to the next line?

时间:2018-06-04 17:15:23

标签: c strtok

int fp = open(file_name, O_CREAT | O_RDONLY, 0644);
if(fp < 0) {
    perror("erro ao abrir o ficheiro");
    _exit(-1);
}
char* notebook = myreadln(fp);
printf("%s\n====\n\n",notebook);
char* token = strtok(notebook, "\n");
while(token != NULL){
    printf("%s\n",token );
    new_line(d,token);
    token = strtok(NULL, "\n");
}
{...}

In this piece of code i load the char* notebook with a file so, i wanna split that char* into lines using "\n", but the output is this:

Isto vai dar sort
$ ls
Jk isto e que vai
$| sort
Isto faz mais 
$| head -1

====

Isto vai dar sort
        Isto vai dar sort
vai dar sort
        vai dar sort
dar sort
        dar sort
sort
        sort

Can some one explain why the token will always losing words instead of going to the next line?

my function new_line: Data d is a pointer to my struct data

void new_line(Data d, char* s){
    char* aux = mystrdup(s);
    printf("\t%s\n",aux);

    int n = conta_palavras(aux); // number of words
    char** args = malloc((n+1)*sizeof(char*)); // create space for n words
    args[n] = NULL;

    char** words = escreve_palavras(aux, args);

    add(d,words);

}

mystrdup:

char * mystrdup (const char *s) {
    if(s == NULL) return NULL;          
    char *d = malloc (strlen (s) + 1); 
    if (d == NULL) return NULL;       
    strcpy (d,s);                    
    return d;                       
}

1 个答案:

答案 0 :(得分:1)

strtok循环本身写得正确,如果没有函数new_line(),它会输出一行,因为它会破坏\n处的字符串。

因此函数new_line()必须干扰它。让我猜怎么样。你希望字符串被分成单词,这就是new_line()试图做的事情。当我用下一个代码实现它时 - 嘿!我得到了你得到的输出。

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

void new_line(char *d, char *str)
{
    char *tok = strtok(str, d);
}

int main() {
    char notebook[] = "Isto vai dar sort";
    char delim[] = " ";
    char* token = strtok(notebook, "\n");
    while(token != NULL){
        printf("%s\n", token );
        new_line(delim, token);
        token = strtok(NULL, "\n");
    }
}

节目输出:

Isto vai dar sort
vai dar sort
dar sort
sort

现在strtok不是&#34;可重入&#34;,这意味着如果您在一个函数中使用它,则无法在另一个函数中安全使用它。因此,让我们立即尝试通过打破空格(以及任何尾随换行符)的字符串来获得您想要的答案:

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

int main() {
    char notebook[] = "Isto vai dar sort";
    char* token = strtok(notebook, " \n");    // added the space
    while(token != NULL){
        printf("%s\n", token );
        token = strtok(NULL, " \n");          // added the space
    }
}

现在节目输出是:

Isto
vai
dar
sort

我认为这就是你想要的。

如果您想在不同的功能中使用strtok,请使用strtok_s(MSVC)或strtok_r(gcc)。