As the title said, I\'m curious if there is a way to read a C++ string with scanf.
I know that I can read each char and insert it in the deserved string, but I\'d wa
You can construct an std::string of an appropriate size and read into its underlying character storage:
std::string str(100, ' ');
scanf("%100s", &str[0]);
str.resize(strlen(str.c_str()));
The call to str.resize() is critical, otherwise the length of the std::string object will not be updated. Thanks to Daniel Trugman for pointing this out.
(There is no off-by-one error with the size reserved for the string versus the width passed to scanf
, because since C++11 it is guaranteed that the character data of std::string is followed by a null terminator so there is room for size+1 characters.)