Objective: To create a simple and efficient URL shortener in C++ that shortens a long URL to a shorter version, making it easy to share. The program will create a random unique string and append it to the base URL to generate the shortened URL.
Introduction
A URL shortener is a tool that generates a shorter alias for a long URL. This makes URLs easier to share and remember. With the growing popularity of social media platforms and messaging apps, the need for shorter links has increased.
This C++ program will help you create a simple URL shortener where users input a long URL, and the program returns a shortened version.
Objective
The primary objective of this program is to create a URL shortener that:
- Accepts a long URL as input.
- Generates a unique short string.
- Combines the base URL with the generated short string to create a shortened URL.
- Displays the shortened URL.
Code for URL Shortener
#include #include #include #include using namespace std; string generateShortURL() { const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string shortURL = ""; srand(time(0)); // Seed for random number generation // Generate a 6-character random string for (int i = 0; i < 6; i++) { shortURL += chars[rand() % chars.length()]; } return shortURL; } int main() { string longURL; // Ask the user for the long URL cout << "Enter the long URL: "; cin >> longURL; // Base URL for shortening string baseURL = "http://short.ly/"; // Generate a short URL string shortURL = baseURL + generateShortURL(); // Display the shortened URL cout << "Shortened URL: " << shortURL << endl; return 0; }
Program Explanation
The program starts by including necessary libraries. The generateShortURL()
function is responsible for generating a random 6-character string from the set of alphanumeric characters.
The program seeds the random number generator using the time(0)
function to ensure that every execution generates a unique shortened URL.
In the main()
function, the program prompts the user to enter a long URL, and the base URL for shortening is defined as http://short.ly/
.
The generateShortURL()
function is called to create a random string, and the shortened URL is displayed by appending the generated string to the base URL.
How to Run the Program
To run this program on your local machine, follow these steps:
- Ensure you have a C++ compiler installed (like GCC or MinGW).
- Create a new file and save it as
url_shortener.cpp
. - Copy the above code into the file.
- Open your terminal or command prompt and navigate to the folder where the file is saved.
- Compile the program using the following command:
g++ url_shortener.cpp -o url_shortener
- Run the program by typing:
./url_shortener
- Enter a long URL when prompted, and the program will display the shortened version.