Search code examples
c++io

How should I read a format string of variable length in C++ from stdin?


sorry for such a stupid question but I couldn't find any obvious answer.

I need to read from stdin first an int n with the size of an array, and then integer values from a string in the format "1 2 3 4 5 6" with n elements.

If I knew the number of parameters at compile time I could use something like a scanf (or the safe alternatives) with a format string like "%d %d %d %d %d %d", but here I will only know that value at run time.

What would be the best way to do this in C++? Performance is important but more than that safety.


Solution

  • How should I read a format string of variable length in C++ from stdin?

    You should not attempt to do such thing. Only ever use constant format strings.

    I need to read from stdin first an int n with the size of an array, and then integer values

    What would be the best way to do this in C++?

    Read one value at a time. Repeat using a loop.