how to cin to int _value:1; C++ -
i have try code, wanna use 1 byte of integer save number, how can value cin, out value cout
struct songuyen{ int _value:1; void input(){ // how can cin value _value; } void output(){ // how can cout value of _value; } } thks got tip.!!
struct songuyen{ int _value:1; void input(){ int value; std::cin >> value; _value = value; } void output(){ std::cout << _value; } }; the integer way not 1 byte 1 bit wide (think why called feature bit fields). bit fields bad programming practice , should avoided possible. if need member width of 1 byte, rather use std::int8_t or signed char. if need 1 with width of 1 bit, use bool (even though waste 7 bits, doesn't matter on modern platforms).
a more c++ approach implement input / output of class 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 this:
int main() { songuyen foo; std::cin >> foo; std::cout << foo; } so looks intuitive (since same syntax applies fundamental types) , modular (you're able write , read stream).
Comments
Post a Comment