If you want to find out if std::istream::getline()
read an array full of characters as demanded but not an end of line character you need to figure out whether the number of stored characters (minus the terminating null) is identical to the extracted characters. That is, the following determines if there are more then 12 characters on the line (the 13th character is needed for the terminating null):
#include <iostream>
#include <string.h>
int main()
{
char array[13];
if (std::cin.getline(array, 13).gcount() == strlen(array)) {
std::cout << "excess characters on the line\n";
}
}
If you next also want to remove the excess characters from the stream you'd use something like std::cin.ignore(std::numeric_limits<std::streamsize>::max());
. Since this is tagged as C, too, I don't know off-hand how to do this with C but I'm pretty sure that there is something similar to gcount()
.
Actually, looking more closely at the spec std::istream:getline()
actually sets std::ios_base::failbit
if it doesn't encounter a newline while reading the character (it also sets std::ios_base:failbit
when no character is read but it doesn't set std::ios_base::failbit
if at least one character is read before end of file is reached). This mean, you also want to clear the stream before ignoring excess characters and you can work off std::ios_base::failbit
and std::ios_base::eof()
:
#include <iostream>
#include <limits>
#include <string.h>
int main()
{
char array[13];
std::cout << "enter password: ";
while (!std::cin.getline(array, 13) && !std::cin.eof())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "password is too long: enter max 12 chars: ";
}
std::cout << "the password is '" << array << "'\n";
}
Since std::ios_base::failbit
is set you need to call clear()
before you can use the stream for anything.