I'm dealing with C++ a bit and am following an introduction in which this code snippet makes me wonder a bit:
cout << "\nPlease enter an article label: ";
// Input the label (15 characters maximum):
cin >> setw(16); // or: cin.width(16);
cin >> label;
The authors don't tell me why for one input line I need (or can use) two times cin, one with the manipulator and one with the place to modify?
Now, in chapter 4 about streams, according to what I've read up to now, I would have expected that these are two separate instances and therefore actions performed. Therefore, at my naive stage, I would have written:
cin >> setw(16) >> label; // according to: cout << setw(16) << label;
Could you explain to me, why two times cin result in just one input line? It seems, that the proposed similar questions here are not similar enough - after checking them.
I can simply accept and reproduce it. But I would like to understand it.
Is it just because in the first line with cin there is no place to write the input two thus it creates the field and which then is "used" from the cin in the second line? And if so, is there a good reason for splitting it in two lines like this?
Performs the same as:
It works like this:
cin >> setw(16)is performed first.setw(16)creates an implementation-defined object that holds the value16. This object is then passed to an overloadedoperator>>that takes incinand that object, assigns the object's value toistream::width(), and then returns theistream&that was passed in, which is ourcin.Something to the effect of this:
After that, the next operation to deal with is
label, and sincecinwas returned from the first operation, what's left is simply: