1
votes

I have a C++ snippet:

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
    char s[2048];
    while (fgets(s, sizeof(s), stdin))
    {
        char *pos = strpbrk(s, ">\r\n");
        if (pos != 0)
        {
            char *end = strrchr( pos, '<' );
            if ( end )
                *end = '\0';
            fputs(pos+1, stdout);
        }

        return 0;
    } 
}

Although when trimming a text file using it, it works with only 1 line e.g. it trims 1 line only.

If I try to trim multiple lines e.g. file with 30 lines in it, it only trims one line still. I am pretty confused, any help would be appreciated.

Example text file:

report2011510222820.html:   <td width="60%" bgcolor="#ffffff" class="tablebody" valign="top">C:\Users\Admin\mon.bat</td>
report2011510222820.html:   <td width="60%" bgcolor="#ffffff" class="tablebody" valign="top">C:\test123.bat</td>

Output:

C:\Users\Admin\mon.bat

Expected Output:

C:\Users\Admin\mon.bat
C:\test123.bat
4
sorry, but this is NOT C++, change your tag to C, or really do this correctly in C++ - Nim
No, you have a C snippet. :) You can usually get much better answers if you actually tell people what language you're using. As long as you're writing C code, tag the question [c], and ask about C. If you pretend it is C++, then you'll mainly get a lot of answers telling you how your code should be rewritten in C++ - jalf
@Nim: There's nothing wrong in using C's IO stuff instead of streams. - Mario
@Mario, I didn't say there was, I just said this is not C++, it's pure C - and hence better tagged as C - or do it properly in C++, no use pretending one is the other... - Nim
@Mario #include <stdio.h> isn't valid C++ however, it would have to be <cstdio>. So this is really C. - Lundin

4 Answers

4
votes

Your return 0; is inside the while() loop so it will always exit after the first run through the loop. You have to move it outside.

To add a line break, replace

if ( end )
    *end = '\0';

with

if ( end )
{
    *end = '\n';
    *(end + 1) = '\0';
}
1
votes

Try putting return 0;` out the the while loop

0
votes

Yout return is inside the "while" loop the end of your program should look like:

  }
   return 0;
}
0
votes

This line is causing your grief:

return 0;

If you indented your source correctly, you would be able to see the error much easier. Here it is corrected and indented:

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
    char s[2048];
    while (fgets(s, sizeof(s), stdin))
    {
        char *pos = strpbrk(s, ">\r\n");
        if (pos != 0)
        {
            char *end = strrchr( pos, '<' );
            if ( end )
                *end = '\0';
            fprintf(stdout, "%s\r\n", pos + 1); /* Fixed formatting */
         }
   }
    return 0;
}

Note that you have tagged this as C++ code, but it is actually just plain old C.