Reputation: 131
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
Upvotes: 0
Views: 891
Reputation: 15872
Short answer: yes.
Use std::string
:
std::string line
while (std::getline(std::cin, line))
{
// do something with line
}
If you are not allowed to use std::string
, then you can either role your own string class, or look at common implementations of std::getline
and mimic them (just without storing it in a std::string
).
Upvotes: 1
Reputation: 11047
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
).
Upvotes: 1