繁体   English   中英

不能在 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;
}

我相信问题是一个名为Fixing operator>>(basic_istream&, CharT*)的 C++20 更新。 它的目的是防止std::cin溢出它正在读入的字符串,并且 cppreference.com 确实列出了std::istreamoperator>>现在有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和作为参数传入的 arrays 或动态 arrays?

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

但是如何将 cin 与作为参数传入的 arrays 或动态 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;
}

如果您有动态大小,请使用仍然适用于cinstd::string

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM