gpt4 book ai didi

c++ - 如何声明一个未知大小的数组,然后输入直到我需要,然后获取数组的大小?

转载 作者:搜寻专家 更新时间:2023-10-31 00:50:58 24 4
gpt4 key购买 nike

我正在尝试声明一个大小为 10,000 的数组。最好是字符数组。然后我可以接受任意大小的输入 n(<=10,100)。我想找到这个 n。

我有一个代码不起作用。

int main()
{
char arr[10000];
cin >> arr;
cin.sync();
int l=0;
for(int i=0; ; i++)
{
if(arr[i]=='\n')
break;
l++;
}
cout << l;
return 0;

输入: hell 我期望输出是 4,但实际输出是 4482。

最佳答案

您不能在标准 C++ 中执行此操作。但是你可以使用

std::vector<char> arr;

arr.resize(/*ToDo - size here*/) 当你需要的时候。 std::vector 内存管理也优于使用具有自动存储持续时间的大型固定大小数组。

也就是说,std::string 可能是您的最佳选择:

std::string the_standard_library_is_fantastic;
std::cin >> the_standard_library_is_fantastic;

其次是

std::cout << the_standard_library_is_fantastic;

您假设 arr 在某种意义上以 '\n' 终止是不正确的。

关于c++ - 如何声明一个未知大小的数组,然后输入直到我需要,然后获取数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56424116/

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