Skip to content

Commit 863ba69

Browse files
Merge pull request #10 from bocaletto-luca/test
Create 19_BasicChatBot.c
2 parents 29467bf + 8600d60 commit 863ba69

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Example/19_BasicChatBot.c

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* Project 19: Basic Chatbot Program
3+
* Author: Bocaletto Luca
4+
* Date: 2025-06-22
5+
* GitHub: bocaletto-luca
6+
*
7+
* Description:
8+
* This program implements a simple text-based chatbot that listens to user input,
9+
* processes it using basic pattern matching, and responds with predetermined answers.
10+
* It continues the conversation until the user types "bye" to exit the chat.
11+
*
12+
* Key Concepts:
13+
* - String parsing and pattern matching (using functions like strcmp() and strstr()).
14+
* - Loop constructs for sustaining interactive conversation.
15+
* - Conditional logic to select appropriate responses based on input.
16+
*/
17+
18+
#include <stdio.h>
19+
#include <string.h>
20+
#include <stdlib.h>
21+
#include <ctype.h>
22+
23+
int main(void) {
24+
char input[256]; // Buffer to store user input.
25+
26+
// Welcoming the user.
27+
printf("Chatbot: Hello, I'm your friendly chatbot. Type 'bye' to exit.\n");
28+
29+
// Main conversation loop.
30+
while (1) {
31+
printf("You: ");
32+
// Read user input from the terminal.
33+
if (fgets(input, sizeof(input), stdin) == NULL) {
34+
// Handle potential input errors.
35+
printf("Chatbot: Error reading input. Exiting.\n");
36+
break;
37+
}
38+
39+
// Remove the trailing newline character, if present.
40+
input[strcspn(input, "\n")] = '\0';
41+
42+
// Convert the input to lowercase for easier matching.
43+
for (int i = 0; input[i] != '\0'; i++) {
44+
input[i] = tolower(input[i]);
45+
}
46+
47+
// Check if the user wants to exit the conversation.
48+
if (strcmp(input, "bye") == 0) {
49+
printf("Chatbot: Goodbye! Have a nice day.\n");
50+
break;
51+
}
52+
53+
// Respond based on pattern matching using strstr() and strcmp().
54+
if (strstr(input, "hello") != NULL) {
55+
printf("Chatbot: Hello there! How can I help you today?\n");
56+
} else if (strstr(input, "how are you") != NULL) {
57+
printf("Chatbot: I'm just a program, but I'm doing fine! How about you?\n");
58+
} else if (strstr(input, "what is your name") != NULL) {
59+
printf("Chatbot: I'm a basic chatbot created by Bocaletto Luca.\n");
60+
} else if (strstr(input, "weather") != NULL) {
61+
printf("Chatbot: I don't have real-time weather data, but it's always a good day for coding!\n");
62+
} else {
63+
// Default response for unrecognized inputs.
64+
printf("Chatbot: I'm not sure I understand. Can you please rephrase your question?\n");
65+
}
66+
}
67+
68+
return 0;
69+
}

0 commit comments

Comments
 (0)