Here is a working example in Windows, as the other answers suggested this is platform dependant.
What I do here is, I've created a function to append a char
to a "string"
. Then I've checked if the keyboard is hit with _kbhit()
, if it's hit, I've recorded the value into c
variable. Afterwards with our custom function, appended the c
variable to str
, and checked if first 3 characters of our str
is "car"
or not.
If it's car, it prints the value you've requested in your question, if user keeps typing, since first 3 characters are now car, it will keep printing the same thing on each key press. You can handle it.
What's the purpose of the counter
? It allows you to add a new character to str
each loop by making sure that if statement works as intended.
I hope this answer helps you, in the near future, I'll also provide an example for Linux.
Windows
#include <stdio.h>
#include <conio.h>
#include <string.h>
char *append_char(char *sz_string, size_t strsize, char c);
int main()
{
char str[] = "";
int counter = 1;
while (1)
{
if (_kbhit()) {
const char c = _getch();
append_char(str, sizeof str + counter, c);
if (strncmp(str, "car", 3) == 0)
{
printf("Do you want to buy it?\n");
}
counter++;
}
}
}
char *append_char(char *sz_string, size_t strsize, char c)
{
size_t len = strlen(sz_string);
if ((len + 1) < strsize)
{
sz_string[len++] = c;
sz_string[len] = '\0';
return sz_string;
}
return NULL;
}
Linux
#include <termios.h>
#include <stdio.h>
#include <string.h>
static struct termios old, new;
void initTermios(int echo)
{
tcgetattr(0, &old);
new = old;
new.c_lflag &= ~ICANON;
if (echo) {
new.c_lflag |= ECHO;
}
else {
new.c_lflag &= ~ECHO;
}
tcsetattr(0, TCSANOW, &new);
}
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
char _getch(void)
{
return getch_(0);
}
char *append_char(char *sz_string, size_t strsize, char c)
{
size_t len = strlen(sz_string);
if ((len + 1) < strsize)
{
sz_string[len++] = c;
sz_string[len] = '\0';
return sz_string;
}
return NULL;
}
int main()
{
char str[] = "";
int counter = 1;
while (1)
{
const char c = _getch();
append_char(str, sizeof str + counter, c);
if (strncmp(str, "car", 3) == 0)
{
printf("Do you want to buy it?\n");
}
counter++;
}
}