不能在 C++20 中将 std::cin 与 char* 或 char[] 一起使用

Can't use std::cin with char* or char[] in C++20

使用 工作:从 std::cin 读取到动态分配的 char 数组 - 或者作为参数传入的数组(参见 MCVE下面)。

#include <iostream>

void read (char str[256]) //or omit the # between the []'s -- no difference
{
    std::cin >> str; //error
}

int main ()
{
    char  s1 [256];
    char* s2 = new char[256];
    char  s3 [256];

    std::cin >> s1;   //OK
    std::cin >> s2;   //error
    read (s3);       

    return 0;
}

我认为问题是针对 std::istreamoperator>> 的名为 Fixing operator>>(basic_istream&, CharT*). Its purpose is to prevent std::cin from overflowing the string it's reading into, and cppreference.com does list new prototypes 的 C++20 更新,现在有 CharT (&s)[N],而不是 CharT* s , 作为参数。

确认:此 MCVE 可与 g++ 10(不支持此功能)一起使用,并且 Visual Studio 使用 Default 作为语言标志;但是使用 /std:c++latest,VS 抱怨:

binary '>>': no operator found which takes a right-hand operand of type 'char *' (or there is no acceptable conversion) 

所以我完全理解编译器的抱怨。但是如何将 std::cin 与作为参数传入的数组或动态数组一起使用?

(另外:当 C++ 准备好读取时,它如何知道数组是动态创建的还是静态创建的?它不应该在声明后进行区分!)

But how do I use cin with arrays passed in as parameters, or dynamic arrays?

不要。如果你有一个 char 数组,给它一个 char 数组,比如

void read (char (&str)[256]) // now we have a reference to an array, so we know its size
{
    std::cin >> str;
}

// or if we don't care about the size, we just want an array

template <std::size_t N>
void read (char (&str)[N]) // now we have a reference to an array, so we know its size
{
    std::cin >> str;
}

如果您有动态尺寸,请使用 std::string,它仍然适用于 cin

void read (std::string& str)
{
    std::cin >> str;
}

(Also: how does C++ know, when it's ready to read, whether an array was created dynamically or statically? It's not supposed to be able to draw that distinction after declaration!)

并不是说它知道它已准备好读取,而是它知道它可以读取的大小。当你给它一个指针时,它只需要相信指针指向足够的内存。如果你给它一个数组,通过引用传递数组,那么编译器就知道它可以读取的大小,因为数组的大小是类型信息的一部分,这与指针不同。不要将数组衰减为指针混淆为数组是指针。它们是两个不同的东西。