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

前端 未结 2 1103
天命终不由人
天命终不由人 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

    0 讨论(0)
  • 2020-12-11 04:15

    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';
    
    0 讨论(0)
提交回复
热议问题