while ((ch = cin.get() != '\n') && (index < MAX-1))
{
array[index] = ch;
index ++;
}
array[index] = '\0';
Your while-loop runs from 0 to MAX-1 (19). This is good because the array can contain 20 elements (0-19). But then you do this: array[index] = '\0'; . But index now == MAX so in other words: array[20] = '\0'; . This will try to write a \0 to element 20 which is the 21th element in the array get it? So not only are you trying to write to memory which is not 'yours', your string doesn't have an 'end of string character' (\0). This will result in memory exceptions and all kinds of other nasty things. (in your case: smilies)
[edit] Also, I think there should be || instead of && inside the condition of while loop.
Nope, it's good the way it is.
Nick Evan
Not a Llama
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
In your reading loop, the input statement needs to be enclosed in parens before comparison to newline character, as so:
while ( ( (ch = cin.get()) != '\n') && (index < MAX-1) )
Othewise, ch was not being assigned the character read in, but rather, the result of the comparison. Remember, assignment has a lower operator precedence than the comparison!
Val
vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
The need to hit enter again is because of the line:
cin.ignore (1000, '\n');
It's a tricky thing trying to deal with newline stuck in the input stream if the user types something more than the number of characters in your input. Taking input one character at a time doesn't make it any easier.
Is there some reason you can't just use getline and grab a bunch of input?
vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228