Yuki
Yuki

Reputation: 93

Line extraction in a char

Hi i'm trying to write a recursive function to extract each line of a string. I don't know why it doesn't work i spent 2 hours trying to find the issue.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int safe_line(char* input, int end_of_line, int num_of_line, int num_sum_safe)
{

    //takes an input, the coordinates of the previous end of the line
    //the number of line already treated
    //and a num_sum_safe which is not important
    
    char temp_line[24];
    int count;
    int actual_line;
    int temp_num_line;
    actual_line = end_of_line;
    temp_num_line = num_of_line + 1;

    if (num_of_line == 3)
    {
        return num_sum_safe;
    }
    
    count = actual_line;

    while (*(input + count) != '\n')
    {   
        *(temp_line + count - actual_line) = *(input + count);
        count++;
    }
    *(temp_line + count - actual_line ) = '\0';
    actual_line += count + 1;

    printf("%s\n", temp_line);

    return safe_line(input, actual_line, temp_num_line, 0);
}

int main()
{
    char input[15] = "n\natt\naa\na as";
    safe_line(input,0 ,0 ,0 );
}

The value that it returns in stdout :

n

att

The expected value should be this :

n

att

naa

na as

Upvotes: 1

Views: 62

Answers (2)

Chris
Chris

Reputation: 36680

While an explanation of your mistake has already been made by Vlad from Moscow, it may be worth noting that this is a lot of effort to avoid using strtok.

E.g.

#include <string.h>
#include <stdio.h>

int main(void) {
    char line[] =
        "hello world\n"
        "foo bar\n"
        "baz wooble\n";

    char *token = strtok(line, "\n");
    while (token) {
       printf("> %s\n", token);
       token = strtok(NULL, "\n");
    }
}

Running this:

$ ./a.out
> hello world
> foo bar
> baz wooble

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

It seems the problem lies in this statement

actual_line += count + 1;
            ^^

You need to write just

actual_line = count + 1;
           ^^^ 

Nevertheless the function declaration is too complicated. Instead of always passing the initial address of the buffer and the current position inside it you could only pass a pointer inside the buffer using the pointer arithmetic.

Here is a demonstration program that shows how you can decrease the number of function parameters by means of the pointer arithmetic.

#include <stdio.h>

void f( const char *input )
{
    int i = 0;

    if (input[i] != 0)
    {
        while (input[i] != '\0' && input[i] != '\n') ++i;

        printf( "%.*s\n", i, input );

        if (input[i] != '\0')
        {
            f( input + i + 1 );
        }
    }
}

int main( void )
{
    char input[] = "n\natt\naa\na as";

    f( input );
}

The program output is

n
att
aa
a as

Upvotes: 1

Related Questions