gpt4 book ai didi

c++ - 为什么 std::(i)ostream 将有符号/无符号字符视为文本而不是整数?

转载 作者:可可西里 更新时间:2023-11-01 15:24:50 25 4
gpt4 key购买 nike

这段代码没有做它应该做的事情:

#include <iostream>
#include <cstdint>

int main()
{
uint8_t small_integer;
std::cin >> small_integer;
std::cout << small_integer;
}

原因很简单:uint8_tunsigned char 的类型定义流将此类型视为文本:
Visual C++ 2015 实现

template<class _Traits> inline
basic_istream<char, _Traits>& operator>>(
basic_istream<char, _Traits>& _Istr, unsigned char& _Ch)
{ // extract an unsigned char
return (_Istr >> (char&)_Ch);
}

还有一个类似的代码转换为char对于 operator << .

我的问题:

  1. 标准是否要求这种行为(流式运算符将有符号/无符号字符视为字符类型而不是整数)?如果是那么:
    1. 这种违反直觉的语义背后的基本原理是什么?
    2. 这是否应该被视为缺陷,是否有人提议更改此语义?

我可能应该添加一点解释为什么我认为它违反直觉。尽管类型名称包含单词 char,signedunsigned部分指定特定的整数语义,这些类型通常用作字节大小的整数。甚至标准也定义了 int8_t/uint8_t通过他们。

UPD:问题是关于 unsigned char 的流运算符重载的行为。和 signed char .

最佳答案

标准 (n3797) 说明如下:

27.7.2.2.3 basic_istream::operator>>

template<class charT, class traits> 
basic_istream<charT,traits>& operator>>(basic_istream<charT,traits>& in, charT& c);

template<class traits>
basic_istream<char,traits>& operator>>(basic_istream<char,traits>& in, unsigned char& c);

template<class traits>
basic_istream<char,traits>& operator>>(basic_istream<char,traits>& in, signed char& c);

12 Effects: Behaves like a formatted input member (as described in 27.7.2.2.1) of in. After a sentry object is constructed a character is extracted from in, if one is available, and stored in c. Otherwise, the function calls in.setstate(failbit).

27.7.3.6.4 Character inserter function templates

// specialization 
template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, char c);

// signed and unsigned
template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, signed char c);

template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, unsigned char c);

1 Effects: Behaves as a formatted output function ( 27.7.3.6.1) of out. Constructs a character sequence seq. If c has type char and the character type of the stream is not char, then seq consists of out.widen(c); otherwise seq consists of c. Determines padding for seq as described in 27.7.3.6.1. Inserts seq into out. Calls os.width(0).

所以第一个问题的答案:是的,标准要求 operator >>operator << char 的行为完全相同, unsigned charsigned char ,也就是说他们读取/写入单个字符,而不是整数。不幸的是,标准没有解释原因。我希望有人能阐明 2 和 3。

关于c++ - 为什么 std::(i)ostream 将有符号/无符号字符视为文本而不是整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36843616/

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