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 ) = '';
actual_line += count + 1;
printf("%sn", temp_line);
return safe_line(input, actual_line, temp_num_line, 0);
}
int main()
{
char input[15] = "nnattnaana 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
7
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] != '' && input[i] != 'n') ++i;
printf( "%.*sn", i, input );
if (input[i] != '')
{
f( input + i + 1 );
}
}
}
int main( void )
{
char input[] = "nnattnaana as";
f( input );
}
The program output is
n
att
aa
a as
1
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 worldn"
"foo barn"
"baz wooblen";
char *token = strtok(line, "n");
while (token) {
printf("> %sn", token);
token = strtok(NULL, "n");
}
}
Running this:
$ ./a.out
> hello world
> foo bar
> baz wooble