oxygen adsorbates on Pt(111) surface


C/C++ Tutorials - Lesson 3
Command Line/Terminal Input Part 1

In the last lesson, you learned how to store information in variables. In this lesson you will learn how to write a program that can capture input from the command line or terminal and store this input into variables.

#include <iostream>

using namespace std;

int main()
{
           // Declaring integer variables x and y
           int x, y, z;
           // Displaying output on terminal
           cout<<"Please enter two integers:";
           // cin stands for c input just as cout stands for c output,
           // cin takes input from the terminal and stores it in a variable.
           // In this example we are getting 2 inputs and saving them in the
           // variables x and y.
           cin>>x>>y;
           // We are multiplying the input and displaying the results.
           z = x*y;
           cout<<"You entered "<< x<<" and "<< y<< endl;
           cout<<"The product of "<< x<<" and "<< y<<" is "<< z<< endl;

           return 0;
}

In the above example, you are asked to input two integers. The program takes these integers, repeats them back to you and then multiplies the integers and displays the product. The example below reads in numbers from a file, input.txt, and computes their sum before writing the sum to second file, output.txt.

#include <fstream>

using namespace std;

int main()
{
           // declaring and initializing a floating-point number, sum, to zero.
           float sum = 0;

           // declaring another floating-point number called number.
           float number;

           // declaring a file input stream infile and openning the file input.txt.
           ifstream infile("input.txt");

           // while not at the end of input.txt.
           while(!infile.eof())
           {
                      // read next number from file.
                      infile>>number;
                      // add number to sum.
                      sum+=number;
           }

           // declaring output stream outfile and openning output.txt.
           ofstream outfile("output.txt");

           // writing to output.txt.
           outfile<<"The sum of the numbers in input.txt is "<
           return 0;
}


© 2013 Dave Schmidt

Web design: Dave Schmidt