0

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

1
  • How are you filling the array? Please give your example Commented Oct 7, 2013 at 19:53

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

3 Comments

I'm using cin.getline() so all the input is immediatly stored in the array. It's not too important but It's for an assignment and my prof loves slashing 60% off anything that he can find wrong.
@JosipDorvak You could just use std::string.
Ok i wasn't sure it counted the termination character I'll try it out. Thanks :)
1

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).

2 Comments

Thanks for the suggestion. I know an actual string would work. But our prof doesn't want us using strings. Really inconvenient. I'm just being overly protected no that he may "try" to overflow the array
Of course he's going to try to overflow the array. That is probably one of the major points of this assignment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.