When reading characters from stdin
, in your case, you have three conditions to protect against if you want to terminate the read on '/'
:
index + 1 < 1000
(to prevent overrun and preserve space for the
nul-terminating char)
(c = getchar()) != '/'
(your chosen terminator); and
c != EOF
(you don't want to read after EOF
is set on the
stream)
Putting those pieces together, you could simply do:
#include <stdio.h>
#define MAXC 1000 /* define a constant (macro) for max chars */
int main (void) {
int c, idx = 0;
char str[MAXC] = ""; /* initialize your array (good practice) */
/* read each char up to MAXC (-2) chars, stop on '/' or EOF */
while (idx + 1 < MAXC && (c = getchar()) != '/' && c != EOF)
str[idx++] = c; /* add to str */
str[idx] = 0; /* nul-terminate (optional here if array initialized, why?) */
printf ("%s", str);
return 0;
}
(I would encourage a putchar ('\n');
after the printf
(or simply add a '\n'
to the format string) to protect against input without a final POSIX end-of-line, e.g. in the event of a stop on '/'
, or on reaching 1000
chars, or reading from a redirected file that does not contain a POSIX EOL)
Example Input File
$ cat ../dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.
Example Use/Output
$ ./bin/getchar_io <../dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.
Look things over and let me know if you have any questions.