Suppose you receive an int from a remote host and you wish to convert it to big-endian order. Here is another portable solution for handling of big and littleendian data formatting. This solution is based on the use of the right shift operator:
// big endianint to_big_endian(int d){ unsigned char buffer[sizeof (int)]; buffer [0] = (char) d >> 24; buffer [1] = (char) d >> 16; buffer [2] = (char) d >> 8; buffer [3] = (char) d; return * (int*)buffer;}
To convert an int to little endian byte ordering, use the following function:
// little endian int to_little_endian(int d){ buffer [0] = (char) d; buffer [1] = (char) d >> 8; buffer [2] = (char) d >> 16; buffer [3] = (char) d >> 24; return * (int*)buffer;}
These functions may not generate the fastest code, but they are portable.Tip #684Intermediate Reading Strings that Contain WhitespacesThe std::getline() functions reads data from an input stream and writes it to a string object. Unlike cin’s >> operator, getline() also reads whitespaces, which makes it useful for reading strings that contain blanks. For example:
#include #include int main(){ std::string name; cout
getline() has three parameters, the third of which is a delimiter serving as a string terminator. By default, the delimiter's value is '
'. You can override this value and define a different delimiter. For example, you can define the sign ' ' (tab) as the delimiter:
std::getline(cin, name, ' ');