Strtok does not drop newline

so I have an input file with a bunch of names and numbers. I started using strtok to split a row so that I can extract all the data from each row. It seems that everything is working correctly, but for some reason does not discard the newline character.

int procFile(PERSON **data, FILE* fpFile) { // Local Declaration char temp[1000]; char proc[15]; char *entry; char *loc; int success = 0; // Statement if(fgets(temp, sizeof(temp), fpFile)) { (*data) = aloMem(); // free entry = temp; loc = strtok(entry, " ()-"); strcpy(proc, loc); loc = strtok(NULL, " ()-"); strcat(proc, loc); loc = strtok(NULL, " ()-"); strcat(proc, loc); sscanf(proc, "%ld", &(*data)->phone); loc = strtok(NULL, "\0"); strcpy((*data)->name, loc); success++; printf("%s1", (*data)->name); } return success; }// procFile 

I tried to print the results to make sure that it was working correctly, and this is my conclusion.

 Brown, Joanne 1South, Frankie 1Lee, Marie 1Brown, Joanne 1Trapp, Ada Eve 1Trapp, David 1White, D. Robert 1Lee, Victoria 1Marcus, Johnathan 1Walljasper, Bryan 1Trapp, Ada Eve 1Brown, Joanne 1Andrews, Daniel 

It prints 1 after each name on a new line, not the right after the name. Can someone explain to me how I can solve the problem?

+4
source share
3 answers

Before tokenizing temp , get rid of the new line as follows:

 char *newline = strchr( temp, '\n' ); if ( newline ) *newline = 0; 

strchr searches for temp for a newline and returns a pointer to it (or NULL if no newline is found). Then we overwrite the new line with 0 (line terminator).

+4
source

According to man fgets :

fgets () reads no more than one character of size from the stream and saves them to the buffer pointed to by s. Reading stops after EOF or a new line. If a new line is read, it is saved in the buffer .

Where you get your new lines from.

+3
source

Add \ r \ n and maybe \ t to the list of delimiters in strtok

+3
source

Source: https://habr.com/ru/post/1482025/


All Articles