What's the deal with setw()?

前端 未结 2 1089
长情又很酷
长情又很酷 2021-01-07 21:42

I recently was bitten by the fact that ios_base::width and/or the setw manipulator have to be reset with every item written to the stream.

2条回答
  •  难免孤独
    2021-01-07 22:39

    The way i see it is : You can always do something like below if you want it to be applied uniformly.

    int width =2;
    while(whatever)
    {
        mystream << std::setw(width) << myval;
    }
    

    but if it was sticky as you mention:

    mystream.width(2);
    while(whatever)
    {
        mystream << myval;
    }
    

    and if i wanted a different width every line I have to keep setting width.

    So essentially both approaches are almost the same, and i would like or dislike them depending on what i am doing now.

提交回复
热议问题