gpt4 book ai didi

c++ - if语句中的getline

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:48:04 25 4
gpt4 key购买 nike

根据我的阅读,在 bool 上下文中使用的 getline() 返回到 void* 的隐式转换。我在网络上的任何地方都没有找到对这一声明的任何真正引用。它到处都说隐式转换不存在,并且在 bool 上下文中指针应该是同类的(如果 ptr == 00 转换为类型指针 ptr).

同样在标准中说在 bool 上下文中它被转换为未指定的 bool 类型。这到底是什么意思?

最佳答案

简而言之:

这意味着您可以在 if 语句中使用 getline(),如果有效,您将进入 if 语句 block 。

在龙:

getline() used in a Boolean context returns an implicitly conversion to void*.

以上在技术上是不正确的(但这是结果)。 getline() 实际上返回对使用它的流的引用。当在 bool 上下文中使用流时,它会转换为可在 bool 上下文中使用的未指定类型 (C++03)。在 C++11 中,它已更新并转换为 bool

  • 如果 getline() 成功,它会返回状态良好的流。当它被转换为 bool like 类型时,它返回一个非空指针 (C++03),当它在 bool 上下文中使用时等同于 true
  • 如果 getline() 失败,它会返回一个处于错误状态的流。当它被转换为 bool like 类型时,它返回一个空指针 (C++03),当它在 bool 上下文中使用时等同于 false.

I haven't found anywhere on the web any real reference to this statement.

  • 21.4.8.9 插入器和提取器[string.io]
    • 定义:std::istream& getline(std::istream&, std::string&)
  • 27.7.2.1 类模板 basic_istream [istream]
    • 定义:std::istream& getline(char_type* s, streamsize n);
  • 27.5.5.1 概述[ios.overview]
    • 定义流在 bool 上下文中的转换方式

Everywhere it says that implicit conversion doesn't exist and that in a Boolean context pointers should be of the same kind (and if ptr == 0 than 0 is converted to type of the pointer ptr).

bool 上下文中的空 void* 等同于 false,任何其他 void* 等同于 true。 (尽管实际上未指定类型,但您可以将其视为 void*(只是为了便于思考)。

Also in the standard says in a Boolean context it is converted to an unspecified-Boolean-type. What does that even mean?

这意味着您可以在任何条件语句中使用它:

if (getline())
{
// If getline worked processes data
}

while(getline())
{
// getline. If it works then processes then try again.
}

关于c++ - if语句中的getline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8204113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com