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

标签 c++ arrays input

我试图声明一个大小为 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/

相关文章:

python - Python 中向后兼容的输入调用

c++ - QSyntaxHighlighter 和多行注释

c - 将 GSL 数组传递给其他函数

c - 使用数组的堆栈实现

c++ - 检查 cin 缓冲区中是否有任何内容

javascript - 如何在输入 PIN 上打点显示要提供的字符数?

C++ Visual Studio 2015 “non-standard syntax; use ' &' to create a pointer to member”

c++ - 等待回调完成的最佳方式

c++ - 查明 DirectInput 设备是否支持 XInput(使用 mingw/gcc)

c - C中的结构数组初始化