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

Top*_*ort 4 c++ 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;
}
Run Code Online (Sandbox Code Playgroud)

我相信问题是一个名为Fixingoperator>>(basic_istream&, CharT*)的 C++20 更新。它的目的是防止std::cin它正在读入的字符串溢出,并且 cppreference.com 确实列出了's 的新原型,这些原型现在具有,而不是作为所采用的参数。std::istreamoperator>>CharT (&s)[N]CharT* s

确认:此 MCVE 适用于 g++ 10(不支持此功能),以及使用默认值作为语言标志的 Visual Studio;但是使用/std:c++latest, VS 抱怨:

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

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

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

Nat*_*ica 7

但是如何将 cin 与作为参数传入的数组或动态数组一起使用?

别。如果你有一个字符数组,给它一个字符数组,比如

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;
}
Run Code Online (Sandbox Code Playgroud)

如果您有动态大小,请使用std::string仍然适用的acin

void read (std::string& str)
{
    std::cin >> str;
}
Run Code Online (Sandbox Code Playgroud)

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

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