gpt4 book ai didi

c++ - C/C++ 读取未知长度的 char* 输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:08:01 24 4
gpt4 key购买 nike

<分区>

我想知道是否可以读取未知大小的字符串,直到有空格或到达换行符。我在 C++ 中所做的是这样的:

char * dynStr;
char buffer[20];

cin >> buffer;
dynStr = new char[strlen(buffer) +1];
strcpy(dynStr, buffer);

但是问题来了,如果输入的input大于20怎么办?所以我认为它应该是这样的:

do
{
cin.get ( buffer, 20, ' '); //im not sure this is the right approach
strcpy(.....); // if is not a first iteration
//add the new buffer to the end of dyn str..
} while( ! read ' ' or '\n' ) <--- this is what I have problem doing

我知道在 c++ 中我可以使用 std::string ,但我想知道如何做这件事,所以如果你有任何想法,请告诉我:)

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com