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
Here a version without limit of length (in case of the length of the input is unknown).
std::string read_string() {
std::string s; unsigned int uc; int c;
// ASCII code of space is 32, and all code less or equal than 32 are invisible.
// For EOF, a negative, will be large than 32 after unsigned conversion
while ((uc = (unsigned int)getchar()) <= 32u);
if (uc < 256u) s.push_back((char)uc);
while ((c = getchar()) > 32) s.push_back((char)c);
return s;
}
For performance consideration, getchar
is definitely faster than scanf
, and std::string::reserve could pre-allocate buffers to prevent frequent reallocation.