开发者

Simple C program - help needed

开发者 https://www.devze.com 2023-03-04 06:07 出处:网络
I have a C++ snippet: #include <stdio.h> #include <string.h> int main(int argc, char *argv[])

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 tri开发者_如何学JAVAmming 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


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';
}


Try putting return 0;` out the the while loop


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

  }
   return 0;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消