After I type my message and the array gets populated the loop will not exit, it will go back to wanting more input. My question is how to make this loop exit when the user is done entering their message and the array has been populated?
#include <stdio.h>
#define MAX 100
int main(void){
int counter = 0;
char C, characterArray[MAX] = {0};
printf("Enter a message: ");
for (C = getchar(); C != EOF || '\n'; C = getchar()){
characterArray[counter++] = C;
}
return 0;
}
C != EOF || '\n'
does not do what you think it does. It evaluates C != EOF
then logical ORs that with '\n'
(which is non-zero, so true) - it's equivalent to:
(C != EOF) || '\n'
What you actually need is:
(C != EOF) && (C != '\n'))
Three other points. First, you should also check to ensure that counter
is not beyond the end of the array, lest you become inflicted with the effects of undefined behaviour.
Secondly, if you're going to ever treat that buffer as a string, make sure you null-terminate it. It's not important in this code segment since you're doing nothing with it. It may not even be necessary if you do use it as a string if, for example, you only get the data once (since the initialisation is zero-filling the buffer).
However, if you ever accept more than one line of input, you should terminate it as part of the input operation.
And thirdly, C
should be an int
rather than a char
. The reason for this is that getchar()
needs to be able to return any character and the EOF
indicator.
The following code shows one way to do what you want:
#include <stdio.h>
#define MAX 20
int main (void) {
int c, counter = 0;
char arr[MAX] = {0};
printf("Enter a message: ");
for (c = getchar();
(c != EOF) && (c!= '\n') && (counter < MAX - 1);
counter++, c = getchar())
{
arr[counter] = c;
}
arr[counter] = '\0';
printf ("You entered: [%s]\n", arr);
return 0;
}
Alternatively, you could replace the for
loop with something like:
counter = 0;
while ((counter < MAX - 1) && ((c = getchar()) != EOF) && (c != '\n'))
arr[counter++] = c;
This uses the short-circuiting nature of &&
to ensure each condition is met before testing the next.