Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtok not discarding the newline character

Tags:

c

so I have an input file with a bunch of names and numbers. I started using strtok to break up the string so that I can extract all the data out of each string. Everything seems to be working correctly, but for some reason it's not discarding 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 printing the results to see if it's working correctly and this is my output.

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's printing the 1 after each name on a newline, rather than right after the name. Can someone explain to me how I can fix the problem?

like image 301
Nathan Avatar asked May 21 '13 19:05

Nathan


2 Answers

According to man fgets:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.

That's where you are getting your newlines from.

like image 98
AlexK Avatar answered Oct 20 '22 01:10

AlexK


Before tokenizing temp, get rid of the newline as follows:

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

strchr searches temp for the newline character, and returns a pointer to it (or NULL if the newline character isn't found). We then overwrite the newline with a 0 (string terminator).

like image 29
John Bode Avatar answered Oct 20 '22 01:10

John Bode