C++ Programming: User Interaction and Working with Variables (Lesson 2)

In programming, input, as well as other data, is stored in variables. There are several different types of variables that store different kinds of information; when you tell the compiler you are declaring a variable, you must include the data type, or just type, along with the name of the variable. The most common basic types available to you are char (stores single character), int (stores integers) and double (numbers with decimal places). Here are some examples of declaring variables: int whole_number; char letter; double number_with_decimals; You use cin (pronunced “C in”) to accept input and it is followed by an insertion operator going in the other direction, >>, followed by the variable into insert the value typed by the user. Here is a sample program demonstrating using a variable: #include using namespace std; int main() { int thisisanuber; cout<> thisisanuber; cout << “You entered ” <<thisisanuber <<“n”; } Shortcut operators: These are shortcut operators for adding any value to a variable: x +=5; // adds 5 to x x -=5; // subtract 5 from x x *=5; // divide x by 5 x++ // add 1 to x; x-- // subtract 1 from x; With these operations, you can make a small calculator in C++: #include using namespace std; int main() { int first_argument; int second_argument; cout << “Enter first argument: “; cin >> first_argument; cout << “Enter second argument: “; cin >> second_argument; cout<< first_argument <<“*” << second_argument << “=” << first_argument*second_argument <<“n”; cout<< first_argument <<“+” << second_argument << “=” << first_argument+second_argument <<“n”; cout<< first_argument <<“/” << second_argument << “=” << first_argument/second_argument <<“n”; cout<< first_argument <<“-” << second_argument << “=” << first_argument-second_argument <<“n”; } Storing Strings: A string can hold multiple characters. C++ string class allows you to work with strings. To use string, you must use the header file. Here is a program that can read a string from the user using cin. #include #include using namespace std; int main() { string user_name; cout <> user_name; cout<< "Hi " << user_name <<"n"; } If you want to put two strings together, known as appending one string onto another, you can use the + sign: #include # include using namespace std; int main() { string user_first_name; string user_second_name; cout <> user_first_name; cout <> user_second_name; string user_full_name = user_first_name + " " + user_second_name; cout << "Your name is "<< user_full_name << "n"; }
This material is from the textbook Jumping into C++ by Alex Allain. I strongly recommend this book if you are new to programming and want to learn more than what I described here.
Click for Lesson 3 Click for Lesson 1
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.