Write a C++ program that will take as input a URL and output the host and the po
ID: 3769412 • Letter: W
Question
Write a C++ program that will take as input a URL and output the host and the port. If there is no port, output that no port is present.
Ex: http://129.128.0.0:80/action?
The double slash (//) is the beginning of the host and the single slash (/) is the end of the host. If there is a port present, the host will end with a colon (:).The port will start right after the colon (:) and end at the single slash (/).
OUTPUT: Host: 129.128.0.0 Port: 80
Example without port: http://129.128.0.0/action?
OUTPUT Host: 129.128.0.0 No port in URL
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
string url;
cout<<"Enter the URL: "; //Read URL
cin>>url;
char c = url.at(0); //Start parsing the string.
int len = url.length(); //Counting the length of string.
int i = 0;
while(!isdigit(c)) //If the parsed character is not a digit.(Till we reach the host address.)
{
i++; //Move forward.
c = url.at(i); //Read the new character.
}
cout<<"Host: ";
while(isdigit(c) || c == '.') //Print the Host address, which should be a collection of digits, and .'s.
{
cout<<c;
i++;
if(i == len) //If end of string is reached stop.
break;
c = url.at(i); //Parse next character.
}
if(c == ':') //If there is a colon, which means when the port is specified.
{
i++;
c = url.at(i);
cout<<" Port: ";
while(isdigit(c)) //Print the port.
{
cout<<c;
i++;
if(i == len)
break;
c = url.at(i);
}
}
else //Else, print there is not port.
cout<<" No port in URL.";
cout<<endl;
}
If you have any further queries, just get back to me.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.