Replacing multiple new lines in a file with just one

后端 未结 5 2010
轻奢々
轻奢々 2021-01-22 12:00

This function is supposed to search through a text file for the new line character. When it finds the newline character, it increments the newLine counter, and when

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-22 12:54

    Dry ran the code: If file starts with a newline character and newLine is 1:

    For the first iteration:

    if (c == '\n') //Will be evaluated as true for a new-line character. 
    {
        newLine++; //newLine becomes 2 before next if condition is evaluated.
        if (newLine < 2) //False, since newLine is not less than 2, but equal.
        {
            printf("new line");
            putchar(c); 
        }
    }
    else //Not entered
    {
        putchar(c); 
        newLine = 0;
    }
    

    On the second iteration: (Assume that it is a consecutive newline char case)

    if (c == '\n') //Will be evaluated as true for a new-line character.
    {
        newLine++; //newLine becomes 3 before next if condition is evaluated.
        if (newLine < 2) //False, since newLine is greater than 2.
        {
            printf("new line");
            putchar(c); 
        }
    }
    else //Not entered
    {
        putchar(c); 
        newLine = 0;
    }
    

    So,

    • Initialize newLine to 0.

提交回复
热议问题