Reading exactly 4 characters from user, using `std::cin`, into a character array

Reading exactly 4 characters from user, using `std::cin`, into a character array

I want to read 4 characters from user, using std::cin, into a character array, and if enters more than 4 characters then to display error.
So I thought about creating a char array of length 4 and to do something like:
char input[4] = "";
std::cin >> input;

But how can I check If he enters more than 4 characters? And if he enters more than 4 characters, won't it over-write the memory after input[4]?

Solutions/Answers:

Answer 1:

You can use std::string;

std::string s;
std::getline(std::cin, s);

if(s.size() != 4)
{
    //ERROR
}

Answer 2:

Possible Solution:

You can use a string for this purpose.

Code:

std::string input = "";
std::getline(std::cin,input);

if(input.size() > 4)
    std::cout << "Error";

Answer 3:

One way to do this is using cin.get(), as follows:

char input[4];
for (int i = 0; i < 4; ++i)
{
    cin.get(input[i]);
}

It is worth mentioning that if you don’t need to use C-style strings, a more elegant approach would be using an std::string:

std::string input = "";
for (int i = 0; i < 4; ++i)
{
    input += cin.get();
}

Answer 4:

An alternative to using std::string is to use the

std::basic_istream& std::basic_istream::get( char_type* s, std::streamsize count )

overload, then discard the rest of the input stream and clear its error flags, like:

#include <iostream>
#include <limits>

int main()
{
    const std::size_t buf_size = 5;
    char buf[buf_size];
    std::cin.get(buf, buf_size); // reads buf_size-1 chars from std::cin and adds a '\0'

    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cin.clear();
    std::cout << buf << std::endl;
}

References

Loading...