Read C++ string with scanf

后端 未结 7 1029
离开以前
离开以前 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:20

    There is no situation under which gets() is to be used! It is always wrong to use gets() and it is removed from C11 and being removed from C++14.

    scanf() doens't support any C++ classes. However, you can store the result from scanf() into a std::string:

    Editor's note: The following code is wrong, as explained in the comments. See the answers by Patato, tom, and Daniel Trugman for correct approaches.

    std::string str(100, ' ');
    if (1 == scanf("%*s", &str[0], str.size())) {
        // ...
    }
    

    I'm not entirely sure about the way to specify that buffer length in scanf() and in which order the parameters go (there is a chance that the parameters &str[0] and str.size() need to be reversed and I may be missing a . in the format string). Note that the resulting std::string will contain a terminating null character and it won't have changed its size.

    Of course, I would just use if (std::cin >> str) { ... } but that's a different question.

提交回复
热议问题