#include <iostream.h>
#include <string.h> // used for string manipulation
void main () {
int a, b; // declaring variables of type integer
char c[50]; // declaring a string of length 49; alternatively, you can use the String class, but for brevity here we forego that
// make sure when you declare a character array, you allocate enough space for all your chars; going past 49, in this case, is ALLOWED, but unexpected results might happen
// note on strings: only at declaration can you give it a value, like
// char c[] = "hello world";
// after declaration, you cannot use a line like
// c = "hello world";
// you must use the strcpy(dest, source) function instead:
// strcpy(c,"hello world");
a=b=0; // setting the values of a and b to 0, called "initialis(z?)ation"
// initialisation is important in C++ because when memory spaces for variables are allocated, they are not set to 0 like in some other languages. If you attempt to output the values of uninitialised variables, whatever was in the memory when it was allocated will be outputted.
cout << "Please input a number:" << endl; // endl is the same as '\n'
cin << a; // inputting a number
cin.ignore(20,'\n'); // flushing the input stream, VERY IMPORTANT
cout << "Please input another number:" << endl;
cin << b;
cin.ignore(20,'\n');
cout << "Please input a string:"<<endl;
cin.getline(c,49,'\n'); // inputting a line; getline's syntax is
// getline(char* s, int l, char delim)
// s is the character array into which the string will be stored; disregard the * for now
// l is the maximum length of the character array (defined above)
// delim is the character with which we end the input (enter key in this case)
cout << "sum is " << a+b << endl;
cout << "difference is " << a-b << endl;
cout << "product is " << a*b << endl;
cout << "your original string is " << endl << c << endl << " and it has length " << strlen(c) << endl; // strlen returns the length of the string
cout << "press enter to exit" << endl;
cin.ignore(1,'\n');
} |