In a group assignment, we have to read input which only consist of the (small) letters a-z and the characters have a max length of 255. I wanted to check with getchar and ASCII, but my partner found a solution using sprintf and scanf, which I do not totally understand:
#include <stdio.h>
int main() {
int result = 0;
unsigned int length = 255;
char input[257];
result = readInput(input, &length);
return 1;
}
int readInput(char *output, int *length) {
char format_pattern[15];
sprintf(format_pattern, "%%%u[^\n]%%n", *length);
printf("Max allowed length is %d\n",*length);
scanf(format_pattern, output, length);
printf("Input length is %d\n",*length);
return 1;
}
Output:
Max allowed length is 255
testinput
Input length is 9
How does the format pattern in sprintf and scanf work?
Especially the three %%%
before u
and the two %%
before n
- I tried changing this to %u[^\n]%n
because two ##
would escape the ´%´, but then I get an error so they have to be there.
The only things I figured out are:
the
%n
can read the characters before it, e.g.:int var; printf("Some Text before%n and after",&var); printf("characters before percent n = %d\n", var);
Output:
Some Text before and aftercharacters before percent n = 16
but in my big example above there isn't a pointer variable, where the amount of text could be stored since
*length
is for%%%u
?The [^\n] means something like "read till new Line"
I googled a lot but did not find a similiar example - could somebody help me?