Reputation: 478
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?
My code looks like this:
cin >> var;
Upvotes: 9
Views: 24599
Reputation: 4995
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
Upvotes: 16
Reputation: 79
hmm you could make 'var' a character array and use a while loop to read input until the array was full maybe?
char var[somenumber + 1];
int count = 0;
while(count < somenumber){
cin >> var[count];
count++;
}
var [somenumber] = '\0';
Upvotes: 2