#include <stdio.h>
#include <stdlib.h>
int main() {
char c; /* 1. */
int count;
char arr[50];
c = getchar(); /* 2. */
count = 0;
while (c != EOF) { /* 3. and 6. and ... */
arr[count] = c; /* 4. */
++count; /* 5. */
}
return (EXIT_SUCCESS); /* 7. */
}
c
should be an int. getchar() returns an int to differentiate between a valid character and EOF
- Read a character
- Compare that character to EOF: if different jump to 7
- Put that character into the array
arr
, element count
- Prepare to put "another" character in the next element of the array
- Check the character read at 1. for EOF
You need to read a different character each time through the loop. (3., 4., 5.)
And you cannot put more characters in the array than the space you reserved. (4.)
Try this:
#include <stdio.h>
#include <stdlib.h>
int main() {
int c; /* int */
int count;
char arr[50];
c = getchar();
count = 0;
while ((count < 50) && (c != EOF)) { /* don't go over the array size! */
arr[count] = c;
++count;
c = getchar(); /* get *another* character */
}
return (EXIT_SUCCESS);
}
Edit
After you have the characters in the array you will want to do something to them, right? So, before the program ends, add another loop to print them:
/* while (...) { ... } */
/* arr now has `count` characters, starting at arr[0] and ending at arr[count-1] */
/* let's print them ... */
/* we need a variable to know when we're at the end of the array. */
/* I'll reuse `c` now */
for (c=0; c<count; c++) {
putchar(c);
}
putchar('\n'); /* make sure there's a newline at the end */
return EXIT_SUCCESS; /* return does not need () */
Notice I didn't use the string function printf(). And I didn't use it, because arr
is not a string: it is a plain array of characters that doesn't (necessarily) have a 0 (a NUL). Only character arrays with a NUL in them are strings.
To put a NUL in arr, instead of limiting the loop to 50 characters, limit it to 49 (save one space for the NUL) and add the NUL at the end. After the loop, add
arr[count] = 0;