我对c ++中的字符串有疑问
我想从用户22字符读取并将它们存储在字符串中
我试过了:
std::string name;
std::cin.getline(name,23);
Run Code Online (Sandbox Code Playgroud)
它显示错误.
将cin.getline与字符串一起使用的解决方案是什么?
您可以使用std::getline(std::istream&, std::string&)从<string>代替.
如果要将事物限制为22个字符,则可以std::string像将其传递给任何C风格的API一样使用:
std::string example;
example.resize(22); // Ensure the string has 22 slots
stream.getline(&example[0], 22); // Pass a pointer to the string's first char
example.resize(stream.gcount()); // Shrink the string to the actual read size.
Run Code Online (Sandbox Code Playgroud)