[英]Is there any way to make a char array without knowing what size it will be
char* a = new char[50];
This is for a school assignment. 这是为了学校作业。 I am not allowed to use strings or vectors or anything else. 我不允许使用字符串或向量或其他任何东西。 Just char array. 只是char数组。
Lets say I want to do cin >> a;
可以说我想做cin >> a;
and I don't know the size of the input. 我不知道输入的大小。 How should I put it in char array? 我该怎么把它放在char数组中? The above only works for a small size of input. 以上仅适用于小尺寸输入。
Should I do this? 我应该这样做吗? char* a = new char[some_large_number];
or is there a better way? 或者,还有更好的方法?
I can only use (dynamic) char arrays. 我只能使用(动态)char数组。
EDIT: The input can be any string like abcd
or even somelongrandomsentecewithoutspsomelongrandomsentecewithoutspacessomelongrandomsentecewithoutspaces
编辑:输入可以是任何字符串,如abcd
甚至somelongrandomsentecewithoutspsomelongrandomsentecewithoutspacessomelongrandomsentecewithoutspaces
This is a little tricky with character arrays: what you need to do is tell cin
that you do not want to receive more than a certain number of characters (49 for a 50-character buffer, because you need space for null terminator). 这对于字符数组来说有点棘手:您需要做的是告诉cin
您不希望接收超过一定数量的字符(50个字符缓冲区为49,因为您需要空终止符)。 When the read is finished, check the length of the string. 读取完成后,检查字符串的长度。 If it is 49, allocate a new, larger, string, copy the old string into it, and continue reading. 如果是49,则分配一个新的更大的字符串,将旧字符串复制到其中,然后继续阅读。 If it is less than 49, the end of string has been reached. 如果小于49,则已到达字符串的结尾。
You can use istream::get
to read the data into your buffer: 您可以使用istream::get
将数据读入缓冲区:
cin.get(a, 50); // You can specify an optional delimiter as a third parameter
Note that you pass 50 for the length, and get
will subtract 1 automatically, because it knows about the space needed for null terminator. 请注意,您为长度传递50,并且get
将自动减1,因为它知道null终止符所需的空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.