CGI | C++ Dealing with user inputs.

During my satuday’s presentation on “CGI using C++” Sir asked me to run a program that shows a table of any given value up to 20 in front of us. I felt nervous and I did in private. The output was in paragraph that was looking ugly. But I was happy in that ugly output. In that program it was not possible to get value from user then I spend my time to make a program in which user can give any integer value to get table of that value.

  • The following is a CGI program called fact.cpp that uses query information supplied by the form.
#include <iostream>
using namespace std;
int main()
string value, s; // declaration
s = getenv("QUERY_STRING"); // s stores the query string extracted from URL
int a =s.length(); // a stores length of query string
int b =s.find("="); // b stores the index number or simply number where “=” is found in the string
value = s.substr(b+1,a); // value stores the value part of the string specified after “=”
int i;
int n= atof(value.c_str()); // atof() converts string to int which gets stored in n
cout<< "Content-Type : text/html \n\n";cout<< "<html> <head> <title> Table </title> </head>";
cout<< "<body bgcolor= green><center> ";
for (int i = 1; i <= 20; ++i) {
cout << n << " * " << i << " = " << n*i << "<br>";
cout<< " </center></body> </html>";
return 0;
  • Compile the file using:
$ g++ fact.cpp -o fact.out
  • Change the permission:
$ chmod 0+wx fact.out
  • Create a form.cpp file that contains the form in CGI format.
using namespace std;
int main()
cout<<"Content-Type: text/html \n\n";
cout<<"<html><head><title> Check the Number</title></head>";
cout<<"<body bgcolor = green ><form action= method=get><center><p> <h3>Enter any Number</h3></p><input type=text name=n><p><h4><input type = submit value= Submit ></h4> </p></form></center></body></html>";
return 0;
  • Compile the file using:
$ g++ form.cpp -o form.out
  • Change permissions:
$ chmod 755 form.out
  • Keep both the files in ~/public_html/cgi-bin/
  • Make sure your ~/public_html/cgi-bin/ have right permissions otherwise run:
$ chmod -R /public_html/
  • Now run your program on browser using:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s