C++ 使用allocate构造字符串时是否可以使用cin?

C++ 使用allocate构造字符串时是否可以使用cin?,c++,C++,我正在阅读有关使用分配器的内容,其中一个练习要求使用分配器从cin读取用户输入。现在我使用默认构造函数创建字符串,然后读入字符串,但我想知道是否可以使用cin的输入直接创建字符串 当前代码: int n = 1; std::allocator<std::string> alloc; auto p = alloc.allocate(n); auto q = p; alloc.construct(q); std::cin >> *q; 使用 对我来说,这不是一个负担。我不确

我正在阅读有关使用分配器的内容,其中一个练习要求使用分配器从cin读取用户输入。现在我使用默认构造函数创建字符串,然后读入字符串,但我想知道是否可以使用cin的输入直接创建字符串

当前代码:

int n = 1;
std::allocator<std::string> alloc;
auto p = alloc.allocate(n);
auto q = p;
alloc.construct(q);
std::cin >> *q;
使用

对我来说,这不是一个负担。我不确定想要使用的动机是什么:

alloc.construct(q, input from cin);
话虽如此,您可以定义一个helper函数

template <typename T> T read(std::istream& in)
{
   T t;
   in >> t;
   return t;
}
模板T读取(std::istream&in)
{
T;
在>>t;
返回t;
}
将其用作:

int n = 1;
std::allocator<std::string> alloc;
auto p = alloc.allocate(n);
auto q = p;
alloc.construct(q, read<std::string>(std::cin));
int n=1;
分配程序alloc;
自动p=分配分配(n);
自动q=p;
alloc.construct(q,read(std::cin));

这是一个。

显然,它读入一个
字符串
,然后move从中构造主字符串;我认为问题的要点是,他们希望避免使用临时字符串too@M.M,我想不出一个办法来避免这个暂时的。你能吗?
std::cin
是一个流,你需要从中逐个提取字符。你可以做的另一件事是
std::getline(std::cin,*q)
唯一的区别是你会抓住整个输入,而不仅仅是一个单词。@KillzoneKid,
std:getline(std::cin,*q)
更接近于我想删除临时字符串的思路。谢谢
template <typename T> T read(std::istream& in)
{
   T t;
   in >> t;
   return t;
}
int n = 1;
std::allocator<std::string> alloc;
auto p = alloc.allocate(n);
auto q = p;
alloc.construct(q, read<std::string>(std::cin));