Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
like image 357
Lucas Menicucci Avatar asked May 27 '12 00:05

Lucas Menicucci


2 Answers

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

like image 152
stan Avatar answered Nov 13 '22 14:11

stan


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';
like image 44
KendalH Avatar answered Nov 13 '22 13:11

KendalH