How do I limit the number of characters entered via cin?

前端 未结 2 1105
天命终不由人
天命终不由人 2020-12-11 03:46

I wish to limit the number of characters that the user can enter, using cin. I might wish to limit it to two characters, for instance. How might I do this?

2条回答
  •  既然无缘
    2020-12-11 04:05

    You can use setw()

     cin >> setw(2) >> var;
    

    http://www.cplusplus.com/reference/iostream/manipulators/setw/

    Sets the number of characters to be used as the field width for the next insertion operation.

    Working example provided by @chris: http://ideone.com/R35NN

提交回复
热议问题