Question

I need to read line by line from a string. I tried the following code but I am getting a error while there are empty lines in between and not able to find what I am doing wrong.

void ReadAllLine(char *szCont)
{
    int rdl = 0; /* read length */
    int len = 0; /* total length */
    char szLine[512] = {};

    len = strlen(szCont);

    int tl = 0; /* temp len */
    while(rdl < len)
    {  
       sscanf(szCont + rdl, "%512s\r\n", szLine);
       rdl += strlen(szLine) + 1;
       printf("%s\n", szLine);
    }  
    return 0;
}

Input :

#Tag01
ENTRY01
ENTRY02

#Tag02
ENTRY11
ENTRY22

#Tag03
ENTRY31
ENTRY32

Output :

#Tag01
ENTRY01
ENTRY02
#Tag02
ENTRY11
ENTRY22
#Tag03
3
ENTRY31
ENTRY32

why is the 3 getting printed here?

Note : Every line is terminated with Windows notation (\r\n) and there are no spacebars before or after any line. The input is read from a file and passed to this function.

Was it helpful?

Solution

Below is your code made even more minimal to reproduce the issue

#include <cstdio>
#include <cstring>

void ReadAllLine(const char *szCont)
{
    int rdl = 0; /* read length */
    int len = 0; /* total length */
    char szLine[512] = {};

    len = strlen(szCont);

    while(rdl < len)
    {
       sscanf(szCont + rdl, "%s", szLine);
       rdl += strlen(szLine) + 1;
       printf("%s\n", szLine);
    }
}

int main()
{
    const char *str ="\n\n#Tag02";
    ReadAllLine(str);
    return 0;
}

This prints

#Tag02
2

The reason is quite simple. sscanf ignores whitespace characters until it finds non-whitespace characters to push in to the output string. Thus, when you call sscanf(szCont + 0, "%s", szLine); for the first time, it skips the 2 \ns occuring first and then moves on to pushing #Tag02 into szLine. Now the value of rdl = 0 + 7 since strlen("#Tag02") = 6. This means szCont + rdl would now be pointing to 2, which gets printed in the next iteration.

The same issue occurs in your case too; your input has 2 \n\n ocurrings, once after ENTRY02, then after ENTRY22.

OTHER TIPS

You are treating carriage return (\r) and line feed (\n) both as line separators, this may vary from operating system to operating system (like windows, unix etc), so be careful, otherwise, the code looks ok. There should not be '3' coming as a separate line, unless you have some whitespace while inputting previous line. Other option is to use fflush before printf statement as below:

fflush(stdout);
printf("%s\n", szLine);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top