You would need to enable non-blocking input to accomplish your goal. You can set this up yourself or rely on the ncurses library.
To set this up yourself, you would need to do something similar to the following:
Code:
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#ifdef EOT
#undef EOT
#endif
#define EOT 4
/*
* @fn non_blocking_input(int fileno, bool enable)
* @brief For enable or disabling non-blocking input on the specified stream.
* @param fileno - file number of stream to alter
* @param enable - set to true or false
*/
int non_blocking_input(int fileno, bool enable)
{
static struct termios old;
if (enable)
{
struct termios tmp;
if (tcgetattr(fileno, &old))
{
return -1;
}
memcpy(&tmp, &old, sizeof(old));
tmp.c_lflag &= ~ICANON & ~ECHO;
if (tcsetattr(fileno, TCSANOW, (const struct termios*) &tmp))
{
return -1;
}
}
else
{
tcsetattr(fileno, TCSANOW, (const struct termios*) &old);
}
return 0;
}
int main()
{
// enable non-blocking input
non_blocking_input(STDIN_FILENO, true);
printf("Enter a sentence ending with a .:\n");
int ch = EOT;
// read single character until a '.' is read; a ctrl-D is interpreted as
// an EOT (End Of Transmission).
while (((ch = getchar()) != EOT) && (ch != '.'))
{
putchar(ch);
}
if (ch != EOT)
{
puts(".");
}
// re-enable blocking input
non_blocking_input(STDIN_FILENO, false);
return 0;
}