C / C++ basic input/output – it’s a little about streams

While I’ve solved some algorithm problems to practice a little with coding, my shame, it turned out I’ve never known how to handle standard input/output streams stdin and stdout, trying to code them similar to console streams cin and cout. OK, doesn’t work directly. Some after I’ve figured out, that cin/cout interact with the same standard streams, but before I’ve met this easiest way I’ve used before, got some experience with C-style IO provided by <stdio.h> header.

Filled a little the blind plot of formatted input and output functions printf() and scanf(). The syntax is not obvious for me from the first glance but found it OK after some lines to accustom:

int a = 5;
float b = 10.6;
float c = 299792.458;
printf("a = %d; b = %.2f; c = %e km/s\n", a, b, c); 
a = 5; b = 10.60; c = 2.997925e+05 km/s

There is a lot of formatting stuff, so it’s the Klondike for those who are fold of ASCII fancy arrangement. The full table of formatting entities I’ve caught away to the sandbox.

The scanf() function takes the same parameters, but the variable to be used as storage for the “scanned” value, has to be transferred as a reference to be able to be written:

    int n;
    scanf("%d", &n);

Also can be used the multiple input separated with ' ' (space), putting multiple input references inside with corresponding format designation. It’s also useful to enter arrays, vectors, etc., so placing scanf() inside the loop body leads to separate calls of it and reading the values from the buffer, which is filled up with values left unclaimed before.

There is a way to flush it all away from buffer using cin.ignore(); or old-style C while (getchar() != '\n'); statement.

This entry was posted in cpp, programming. Bookmark the permalink.