Read C++ string with scanf

后端 未结 7 1018
离开以前
离开以前 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 12:57

    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.

提交回复
热议问题