I have a character array that can hold 1000 elements (+1 for the '\0'). The array will be filled by user input. I was wondering if there is any way of checking if the input is more than what the array can hold. If I do try to add it, the program will crash before I can compare its size. I was thinking expand the array and see if the input is less than 1000 characters, but that idea doesn't seem like a really good one too me.
EDIT:
im using std::cin.getline()
to get input from the user
and can't use the Sting
class
I think one way to check it is to find the index of \0
in your array. If the position is equal or greater than 1000
, then you should not add more chars to it.
If you are using cin.getline()
you can use a variable n
to specify the maximum of chars you want
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
Here you can set n=1001
(it also counts the termination char \0
).