Welcome to this tutorial on building a simple chatbot using C++. In this tutorial, we will create a basic chatbot program that responds to user input with pre-defined responses. The chatbot will interact with users, providing answers to specific queries.
Objective
The objective of this program is to demonstrate how to create a basic chatbot using C++. The program will:
- Receive input from the user.
- Respond with a predefined set of responses based on the input.
- Exit the chat when the user types “exit”.
Code for Simple Chatbot in C++
#include
#include
using namespace std;
int main() {
string user_input;
cout << "Hello! I am your chatbot. Type 'exit' to end the conversation.\n";
cout << "How can I help you today?\n";
// Start the conversation loop
while (true) {
cout << "> ";
getline(cin, user_input); // Get user input
// Check if user wants to exit the conversation
if (user_input == "exit") {
cout << "Goodbye! Have a great day!\n";
break;
}
// Respond to user input
if (user_input == "hello") {
cout << "Hi there! How can I assist you?\n";
} else if (user_input == "how are you") {
cout << "I'm doing great, thank you for asking! How about you?\n";
} else if (user_input == "your name") {
cout << "I am a chatbot created to assist you!\n";
} else {
cout << "Sorry, I didn't understand that. Can you ask something else?\n";
}
}
return 0;
}
Explanation of the Program Structure
The chatbot program is simple and consists of the following key parts:
- Header Files: We include the necessary header files
#include <iostream>
for input and output, and#include <string>
to use the string data type. - Main Function: The
main()
function is where the execution of the program begins. - User Input: We use
getline(cin, user_input)
to capture the entire line of text entered by the user. - While Loop: The program runs in a loop that continues to prompt the user for input until they type “exit”.
- Conditional Statements: Using
if-else
statements, the program matches the user’s input to a predefined set of responses. If the input doesn’t match any predefined command, it asks the user to rephrase their question. - Exit Condition: If the user types “exit”, the program will print a goodbye message and break out of the loop, ending the conversation.
How to Run the Program
Follow these steps to run the chatbot program:
-
- Write the C++ code in a text editor and save it as
chatbot.cpp
. - Open a terminal or command prompt.
- Navigate to the directory where
chatbot.cpp
is saved. - Compile the code using the C++ compiler. For example, if you’re using GCC, run:
- Write the C++ code in a text editor and save it as
g++ -o chatbot chatbot.cpp
-
- Run the compiled program by typing:
./chatbot
- Interact with the chatbot by typing your queries. Type
exit
to end the conversation.