make_unique可以存储文字或 iostream 输入吗?
can make_unique store the literals or iostream inputs?
当我使用 char 类型的普通指针来存储来自<iostream>
bycin>>ptr
的输入时,它被转换为数组。
我推断这是因为cout<<ptr;
给出了存储的字符串并且没有给出地址。地址由cout<<&pointer;
.
但是当我改用make_unique
时,它给出了错误。 为什么他们的行为相同。 请解释这一点,以及使用 make_unique 将字符串输入存储为字符数组的正确方法是什么。 我已经附加了使用的代码。
#include<iostream>
#include<string>
#include<memory>
using namespace std;
int main(){
//using of std::string
string str;
cout<<"Enter a str: ";
cin>>str;cout<<endl;
cout<<str<<"n";
// using of ordinary pointer
char* str2;//as if u r assigning array to a pointer
cout<<"Enter a str: ";
cin>> str2;cout<<endl;
cout<<str2;
cout<<endl;
//using of arrays
char c[] = "ghfgtgbbb";
cout<<c;
char* cPtr = c;
cout<<"n"<<cPtr;
cout<<endl;
//using of mak_unique (gives errors)
auto str3Ptr = make_unique<char>();
cout<<"Enter a str: ";
cin>> str3Ptr;cout<<endl;
cout<<str3Ptr;
cout<<endl;
return 0;}
首先,
// using of ordinary pointer
char* str2;//as if u r assigning array to a pointer
cout<<"Enter a str: ";
cin>> str2;cout<<endl;
cout<<str2;
cout<<endl;
可能"有效",但它实际上是未定义的行为。char* str2;
创建一个指向某物的指针,但我们不知道是什么。 尝试使用cin>> str2
将数据存储在其中是未定义的行为,因为您无权写入任何str2
指向的内容。 所以应该避免这个代码块。
现在让我们看看
//using of arrays
char c[] = "ghfgtgbbb";
cout<<c;
char* cPtr = c;
cout<<"n"<<cPtr;
cout<<endl;
这更好,c
是一个 10 个字符的数组,并且cPtr
初始化为指向它,因此它是一个有效的指针。 你不用它输入,但你可以,但你必须确保不超过 9 个字符(你必须为空终端留出空间(。
现在我们将查看unique_ptr
代码。 在
//using of mak_unique (gives errors)
auto str3Ptr = make_unique<char>();
cout<<"Enter a str: ";
cin>> str3Ptr;cout<<endl;
cout<<str3Ptr;
cout<<endl;
你基本上做了与第一个代码块相同的事情。auto str3Ptr = make_unique<char>();
创建指向单个char
的唯一指针。 所以至少你已经初始化了变量,但它不会大到足以存储输入。 您需要使用数组版本并为所需的输入分配足够的空间。 那看起来像
auto str3Ptr = make_unique<char[]>(80);
^^ number of elements to allocate
您也不能将其与cin
或cout
一起使用,因为它不提供重载来执行此操作。 您要么必须编写自己的代码,要么如果指针类型存在重载,则可以使用get
来获取指向存储在unique_ptr
中的内容的实际指针。
所以,这给我们留下了
//using of std::string
string str;
cout<<"Enter a str: ";
cin>>str;cout<<endl;
cout<<str<<"n";
这是在C++中处理字符串的正确方法。 它将处理分配和解除分配,并构建为与标准流一起使用。
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- make_unique可以存储文字或 iostream 输入吗?
- iostream输入问题
- C++ 仅使用 #iostream 检查输入是否为浮点数
- 将iostream输入代码从c++移植到c#
- 为什么boost::asio::ip::tcp::iostream解析输入?
- 使用IOSTREAM在同一行进行输出和输入