C, strstr, strings question

Started by
5 comments, last by Bregma 17 years, 10 months ago
Here is a C fonction I have programmed and written here in a simplified manner :

void sub(char *desc, char *text) { 
     char string[255]; 
     char *temp; 
         
     while (!feof(stdin)) { 
            fgets(string, 255, stdin); 
 
         if (!feof(stdin)) { 
             temp = strstr(string, desc); 
 
             if (temp == NULL) { 
                 printf("%s", string); 
             }    
             else {    
                 printf("%s%s", text, temp); 
             } 
         } 
     }    
 } 
What I am getting is after a line that goes into the else clause ( meaning strstr(string, desc) wasn't null ) the following line there are some garbage characters which are printed, even if it only prints the string which should'nt be affected by strstr. I took strstr usage's ( returning it to a char * ) directly from an example on the net. What am I doing wrong here ?
WHO DO THEYTHINK THEY'REFOOLING : YOU ?
Advertisement
What characters exactly are you referring to with "garbage characters"? The newline/carriage return stuff will show up as odd characters.
I can't see anything wrong with the code. Your garbage characters are probably in the string recieved from fgets. Like Evil mentioned, they're probably non printing characters like newline and CR. Try manually filling string with some test data and see if that fixes it.
Shouldn't printf stop at the carriage return, end of line characters, thus, I should'nt be able to see them ?

WHO DO THEYTHINK THEY'REFOOLING : YOU ?
Quote:Original post by perfectly_dark
I can't see anything wrong with the code. Your garbage characters are probably in the string recieved from fgets. Like Evil mentioned, they're probably non printing characters like newline and CR. Try manually filling string with some test data and see if that fixes it.


I'm doing this under linux, every time I work with strings under Linux I tend to get some crap at the end of my strings every now and then.

My guess is that some library or whatnot isn't implemented the same as under Windows.
WHO DO THEYTHINK THEY'REFOOLING : YOU ?
Linux and Windows use different characters for a new line. I think Windows uses a Carriage Return Line Feed whereas Unix derivatives use just a Line Feed. So if you're reading a file or stream that uses CRLF as a newline using the Linux libraries, you'll see the Carriage Return character.
Quote:Original post by Bleakcabal
Shouldn't printf stop at the carriage return, end of line characters, thus, I should'nt be able to see them ?


No. printf() prints everything you tell it to, up to the first '\0'.

Think about it. What do you expect printf("\n\n") to print? What about printf("%s\n", "\n")?

Stephen M. Webb
Professional Free Software Developer

This topic is closed to new replies.

Advertisement