[英]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::istream
的operator>>
現在有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;
}
如果您有動態大小,請使用仍然適用於cin
的std::string
void read (std::string& str)
{
std::cin >> str;
}
(另外:C++ 是如何知道,當它准備好讀取時,數組是動態創建的還是靜態創建的?它不應該能夠在聲明后得出這種區別!)
不是它知道它可以讀取,它知道它可以讀取的大小。 當你給它一個指針時,它只需要相信指針指向足夠的 memory。 如果你給它一個數組,通過引用傳遞數組,那么編譯器就知道它可以讀取的大小,因為數組的大小是類型信息的一部分,與指針不同。 不要將數組衰減為指向 arrays 的指針混淆為指針。 他們是兩個不同的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.