I've to read a string of brackets to analyze that. How can I read a string to be inserted in an array generated dynamically?
How can I avoid all characters from reading except for brackets using scanf? [ ] { } ( )
Thank you.
edit: I have to read a series of brackets from keyboard but I don't know the length. So I've to create an array generated dynamically ( this is a requirement ) to contains only the space of the brackets. While I'm reading I want to accepts only brackets and avoid all other characters, is this possibile with scanf with the regex?
Code cannot. At some level, code is reading whatever the user types including
[ ] { } ( )
and characters that are not. The best is for code to read the input and then selectivity operate on it even if that means reading and tossing the data. In any case, OP certainly wants to read a'\n'
too to know when to stop.Using
fgets()
is best for user input @Michael Walz, but OP reports thatscanf()
must be used.scanf()
has a scan set specifier that allows for reading only select characters, leaving others to remain instdin
. A scan set is"%[...]"
with the...
as the desired characters. If]
is desired to be part of the scan set, it should be the first.Since it is not stated an upper bound of input length, code can live dangerously and simply re-allocate memory as needed to accommodate user input by reading 1 character at a time.
Below is some not so efficient code that meets the goal: