如何为指向char数组的unique_ptr填充内容?
解决
unique_ptr<char[]>无法直接用cin输入的问题 你遇到的问题是因为std::unique_ptr<char[]>没有直接重载std::istream的>>运算符,所以不能直接把ptr传给cin。要解决这个问题,你需要通过unique_ptr的get()方法获取底层的char*指针,再用来接收输入。
方法1:用cin >>接收单个单词
修改代码如下,调用get()拿到底层指针:
#include <iostream> #include <memory> #define LEN 100 using std::cout, std::cin; int main() { std::unique_ptr<char[]> ptr {new char[LEN]}; cout << "Enter a word: \n"; // 用get()获取底层char*指针 cin >> ptr.get(); // 验证输入 cout << "You entered: " << ptr.get() << '\n'; }
方法2:用getline接收整行输入
如果要用getline,需要注意:如果之前用过cin >>,输入缓冲区里会残留换行符,导致getline直接读取空行。可以先调用cin.ignore()清空缓冲区。另外getline需要传入底层指针和最大长度:
#include <iostream> #include <memory> #include <limits> // 用于numeric_limits #define LEN 100 using std::cout, std::cin, std::endl; int main() { std::unique_ptr<char[]> ptr {new char[LEN]}; cout << "Enter a line: \n"; // 清空输入缓冲区的残留换行 cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 用getline接收整行,第二个参数是最大读取长度 cin.getline(ptr.get(), LEN); cout << "You entered: " << ptr.get() << endl; }
安全提示
为了避免输入长度超过数组大小导致缓冲区溢出,建议在使用cin >>时先设置输入宽度:
cin.width(LEN); // 限制最多读取LEN-1个字符(留一个位置存结束符'\0') cin >> ptr.get();
内容的提问来源于stack exchange,提问作者Giovanni Scordilli
相关产品推荐
相关产品推荐

