Sovengarde
Sovengarde

Reputation: 67

Determine how many characters are given in cin?

Suppose i have written:

    ...
    char c;
    while(condition){
       cin>>c;
       //do stuff
       ...
    }
...

If 2 characters are give in cin, the next cin will take the second character without me giving any. So, i tried this:

...
char c;
while(condition){
   cin<<c
   //do stuff
   ...
   cin.ignore("999 \n");
}
...

In this case the program will work keeping only the first input but, is there a way to check how many characters the user inputs in cin in order to print an appropriate message?

for example, if the input is ab it will print something like "Please type only one character".

Upvotes: 0

Views: 4019

Answers (2)

Killzone Kid
Killzone Kid

Reputation: 6240

I think what you want is std::cin.rdbuf()->in_avail() which will tell you how many chars are still in std::cin buffer. If you are going to read just 1 char, and enter 1 char, the result would be 1, because of unread \n. So keep this in mind when calculating.

#include <iostream> 

int main()
{
    char c;
    std::cin >> c;
    std::cout << "cin still contains " << std::cin.rdbuf()->in_avail() << " chars" << std::endl;
}

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234715

Read a std::string and validate:

 while(condition){
     std::string s;
     std::cin >> s;
     if (s.length() != 1){
         // oops - make sure s[0] is not taken
     }
     c = s[0];

     // do stuff         
  }

Upvotes: 4

Related Questions