Read C++ string with scanf

后端 未结 7 1027
离开以前
离开以前 2020-11-28 12:35

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

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 13:12

    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.)

提交回复
热议问题