如何限制通过cin输入的字符数? [英] How do I limit the number of characters entered via cin?
本文介绍了如何限制通过cin输入的字符数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望使用 cin
限制用户可以输入的字符数。例如,我可能希望将其限制为两个字符。我该怎么办?
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?
我的代码如下:
cin >> var;
推荐答案
您可以使用 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.
工作示例由@chris提供: http://ideone.com/R35NN
Working example provided by @chris: http://ideone.com/R35NN
这篇关于如何限制通过cin输入的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文