1
while((fscanf(datafile, " %127[^;] %[^\n]", name, movie)) == 2) {   
             printf("%s\n", movie);
             for(i=0; i<=strlen(movie); i++) {
                if(movie[i]!='\0'){ 
                   printf("%c", movie[i]);  
                } else {
                   printf("44 %d", i);
                   break;   
                }
             }
             printf("%d\n", strlen(movie));
             break;
             insert_tree(tree, name, movie);                           
    } 

i have this code fscanf reads in all the strings after semicolon but it also reads in long blank spaces after a sentence has ended in the file

how can i make this stop at just the right point??

oewifjaew
  • 29
  • 4

2 Answers2

1

Can't. To read a line including spaces, yet stop when the lines ends with spaces requires knowing that the trailing spaces exist without reading them.

Instead, read the line and post-process it.

char buf[127+1+1];
fgets(buf, sizeof buf, stdin);
buf[strcspn(buf, "\n")] = '\0';  // Drop potential \n

// get rid of trailing ' '
/// This is inefficient, but shown for simplicity - certainly OP can do better.
char *p;
while ((p = strrchr(buf, ' ')) != NULL) *p = '\0';
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • To "trim" a string, see http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way (Best answer is at http://stackoverflow.com/a/26984026/2410359) wink-wink) – chux - Reinstate Monica Sep 03 '15 at 16:05
0

Firstly, never use scanf or fscanf. Read a line from the file and then use sscanf on that. This way your code won't go berserk on input errors and throw away large amounts of data. It'll also generally simplify your format string.

As to the long blank spaces, I'd suggest you just looked for the last non-blank space in the strings and terminated the string there. Sadly you'll have to do this by hand as there's no standard library function.

It'd be helpful to know the format of these lines. If it's just 'name;movie' (and you're guaranteed not to have ; in the name or the movie part) you could use strchr to find the separator

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61