Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does sscanf() support "recursive" buffer?

Tags:

c

scanf

I make some research in order to look for the sscanf() source code . But I could not find the answer to my question.

when we use sscanf() in this way:

char str[50] = "5,10,15";
int x;
sscanf(str,"%d,%s",&x,str);

Does sscanf() support "recursive" buffer str ?

like image 289
MOHAMED Avatar asked Nov 27 '12 10:11

MOHAMED


People also ask

Why gets is not working after scanf?

This happens because every scanf() leaves a newline character in a buffer that is read by the next scanf. How to Solve the Above Problem? We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note the extra space).

Does Sscanf move pointer?

You are correct: sscanf indeed does not "move", because there is nothing to move. If you need to scan a bunch of ints, you can use strtol - it tells you how much it read, so you can feed the next pointer back to the function on the next iteration.

Does scanf read a line?

scanf() It is used to read the input(character, string, numeric data) from the standard input(keyboard). It is used to read the input until it encounters a whitespace, newline or End Of File(EOF).


1 Answers

It doesn't break from self modifying buffer. But to make it (tail)recursive, you'd have to read to the end of the string.
The code fragment:

char str[]="5,10,15";
int a[10]={0},x = 0; 
while (sscanf(str,"%d,%s",a+ x++,str)>1);

reads all the integers.

Since this is not really recursive and the string to be read doesn't overwrite the asciiz in the string, I believe this is "safe" in the meaning: only try this at home.

like image 68
Aki Suihkonen Avatar answered Oct 01 '22 10:10

Aki Suihkonen