C++ Logo

std-discussion

Advanced search

Re: int8_t outputs char via <iostream>

From: Yongwei Wu <wuyongwei_at_[hidden]>
Date: Sat, 23 Dec 2023 13:45:13 +0800
int8_t is just an alias of signed char, and char, signed char, and unsigned
char are all character types (as the names imply). Your first code snippet
behaves as expected, as far as the current C++ standard is concerned. I
believe you were mistaken somewhere about the second code snippet, and I
cannot reproduce what you described.

You might regard the problem as a design defect, but this is a fact already
(partly as the price we paid for C compatibility). If one needs an 8-bit
integer type that does not behave like a char, a new user-defined type is
then needed, as well as some utility functions to support stream
input/output. They are quite easy to write (though it is a regret that they
do not exist in the standard library).

On Sat, 23 Dec 2023 at 08:35, Olavi Esker via Std-Discussion <
std-discussion_at_[hidden]> wrote:

>
>
>>> Hello,
>>> With <iostream> int8_t prints out char according to ascii number.
>>> Similarly it reads a single char, which cannot be static int converted. The
>>> compiler gives no warning whatsoever. But when <cstdio> is used with scanf
>>> %hhd and printf %d it works perfectly. Is this really the intended
>>> <iostream> functioning? In Rust i8 and C <stdio.h> int8 works fine, too.
>>> #include <iostream>
>>> #include <cstdint>
>>>
>>> int main()
>>> {
>>> std::int8_t myInt{65};
>>> myInt += 1;
>>> std::cout << myInt;
>>> }
>>>
>>> Guess what this returns?
>>> Character "B".
>>>
>>> int main()
>>> {
>>> std::int8_t myInt{};
>>> std::cin >> myInt;
>>> std::cout << myInt;
>>> }
>>> This will also read a character, and
>>> print the characters ascii value.
>>> So if I give it 35, it read it only first '3', and prints out 51.
>>>
>>>
>>> The g++ 13.2 compiler gives also no warning of this whatsoever with the
>>> flags:
>>> "-std=c++20",
>>> "-pedantic-errors",
>>> "-Wall",
>>> "-Wpedantic",
>>> "-Wshadow",
>>> "-Wcast-align",
>>> "-Wlogical-op",
>>> "-Wno-unused-parameter",
>>> "-Weffc++",
>>> "-Wextra",
>>> "-Wconversion",
>>> "-Wsign-conversion".
>>>
>>>
>>> It does seem like a mistake to have `signed char` and `unsigned char`
>>> display as characters rather than numbers, since `char` is a distinct type.
>>> And so `char` could display as a character and the other two as integers.
>>>
>>> Wish you can change this, or at least have a warning, because <iostream>
>>> functions fine for higher bitted integers.
>>>
>>> Thanks.
>>> OE
>>>
>>> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>


-- 
Yongwei Wu
URL: http://wyw.dcweb.cn/

Received on 2023-12-23 05:45:27