HoangHieu
HoangHieu

Reputation: 2840

how to cin to int _value:1; C++

I have tried a code, It wanna use 1 byte of integer to save a number, how I can get value with cin, out value with cout

struct SoNguyen{
    int _value:1;
    void Input(){
         // How I can cin value to _value;
    }
    void Output(){
        // How I can cout value of _value;
    }
}

thks any got a tip.!!

Upvotes: 0

Views: 4828

Answers (2)

Fytch
Fytch

Reputation: 1087

struct SoNguyen{
    int _value:1;
    void Input(){
        int value;
        std::cin >> value;
        _value = value;
    }
    void Output(){
        std::cout << _value;
    }
};

The integer is by the way not 1 byte but 1 bit wide (think about why they called this feature bit fields). Bit fields however are bad programming practice and should be avoided as good as possible. If you need a member with the width of 1 byte, then rather use std::int8_t or signed char. If you need one with with the width of 1 bit, use bool (even though you waste 7 bits, it doesn't really matter on modern platforms).

A more C++ like approach to implement input / output of a class would contain operators:

struct SoNguyen{
    int _value:1;
};
template<typename CharT, typename CharTraits>
std::basic_istream<CharT, CharTraits>& operator>> (std::basic_istream<CharT, CharTraits>& Stream, SoNguyen& Object)
{
    int Value;
    Stream >> Value;
    Object._value = Value;
    return Stream;
}
template<typename CharT, typename CharTraits>
std::basic_ostream<CharT, CharTraits>& operator<< (std::basic_ostream<CharT, CharTraits>& Stream, SoNguyen const& Object)
{
    return Stream << Object._value;
}

The calling syntax would then look like this:

int main()
{
    SoNguyen foo;
    std::cin >> foo;
    std::cout << foo;
}

So it looks intuitive (since the same syntax also applies for fundamental types) and modular (you're able to write to and read from any stream).

Upvotes: 3

R Sahu
R Sahu

Reputation: 206567

You'll have to read a primitive type - int, char, or short. Then assign the primitive type to the bit field.

void Input() {
   int i;
   std::cin >> i;
   _value = i;
}

or

void Input() {
   short i;
   std::cin >> i;
   _value = i;
}

etc.

The output is straight forward.

void Output() {
   std::cout << _value;
}

Upvotes: 2

Related Questions