加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C打印布尔值,显示什么?

发布时间:2020-12-16 09:13:50 所属栏目:百科 来源:网络整理
导读:我将bool打印到输出流,如下所示: #include iostreamint main(){ std::cout false std::endl;} 标准是否要求流上的特定结果(例如0表示错误)? 解决方法 标准流有一个boolalpha标志,用于确定显示的内容 – 当它为假时,它们将显示为0和1.当它为真时,它们将显示
我将bool打印到输出流,如下所示:

#include <iostream>

int main()
{
    std::cout << false << std::endl;
}

标准是否要求流上的特定结果(例如0表示错误)?

解决方法

标准流有一个boolalpha标志,用于确定显示的内容 – 当它为假时,它们将显示为0和1.当它为真时,它们将显示为false和true.

还有一个std :: boolalpha操纵器来设置标志,所以这个:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"n";
    return 0;
}

…产生如下输出:

0
false

对于它的价值,当boolalpha设置为true时产生的实际单词是本地化的 – 即< locale>有一个num_put类别来处理数字转换,所以如果你使用正确的语言环境灌输一个流,它可以/将打印出true和false,因为它们在该语言环境中表示.例如,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "n";
    std::cout << std::boolalpha;
    std::cout << false << "n";
    return 0;
}

…至少在理论上(假设你的编译器/标准库接受“fr”作为“法语”的标识符)它可能会打印出faux而不是false.但是,我应该补充一点,对此的真正支持充其量是不均衡的 – 即使是Dinkumware / Microsoft库(在这方面通常相当不错)也会为我检查的每种语言打印错误.

使用的名称虽然在numpunct facet中定义,但是如果你真的希望它们能够正确地打印出特定的语言,你可以创建一个numpunct facet来做到这一点.例如,(我相信)法语至少相当准确的一个看起来像这样:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(),new my_fr));

    std::cout << false << "n";
    std::cout << std::boolalpha;
    std::cout << false << "n";
    return 0;
}

结果是(正如你可能预期的那样):

0
faux

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读