c - How to read -1 char from stdin? -
i desperate trying figure out how can read char value -1/255 because functions means eof. example if enter characters extended ascii low high (decimal value) end -1/255 eof not array. created small code express problem.
#include <stdio.h> #include <string.h> #include <stdlib.h> #define buffersize 1024 int main(void){ char c; unsigned int *array = (unsigned int*)calloc(buffersize,sizeof(unsigned int)), = 0; while (1){ c = fgetc(stdin); if (c == eof) break; array[i] = c; i++; } array[i] = 0; unsigned char *string = (unsigned char *)malloc(i); for(int j = 0;j < i;j++) string[j] = array[j]; free(array); //working "string" return 0; }
i mode
if (c == eof) break;
like this
c = fgetc(stdin); array[i] = c; i++; if (c == eof) break;
but ofcourse, program read control character user input keyboard (for example ctrl+d - linux). tried opening stdin binary found out posix systems carries files binary. using qt, gcc , ubuntu. tried fread, read, fgets ended same. said, need read enter on stdin , put char array except when enter control character (ctrl+d) end reading. advices appreciated.
edit: noted in comment @tonyb should not declare c
char
because fgetc()
returns int
, changing int c;
should make possible store eof
in c
.
i didn't see declared c
char c;
credit goes @tonyb.
original answer: although problem addressed in comments, , added solution answer, think confused, eof
not character, it's special value returned i/o functions indicate end of stream.
you should never assume it's vaule -1
, there macro reason, should rely on fact these functions return eof
not -1
.
since there no ascii representation value -1
can't input character, can parse input string {'-', '1', '\0'}
, , convert number if need to.
Comments
Post a Comment