Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote