josh1billion's C++ Beginner's Tutorial Spot



Lesson 3: Input/Output



Input
Input is simply the word we use to describe whenever the person playing the game or using the program puts in some kind of information into the program/game. This could mean pressing a keyboard button, moving the mouse, entering the player's name, or anything else that involves the user (the player) interacting with the program/game. Right now, we will be focusing on entering values such as the user's name. So let's ask the user their name, shall we?
#include <iostream.h>
#include <string.h>

int main()
{

string name; cout << "Please enter your name: ";
cin >> name;
cout << "Why hello there, " << name << "!";
return 0;
}


Let's examine this example step by step as usual.
There is a new include file this time around, called string.h. string.h allows us to use the string variable type. What is a string? A string is simply a group of characters. As you should know, a character can be a letter or number. So string variables can store words, like the user's name, as we did in this example. A few lines down the "string name;" line is implemented. This line simply creates a string variable named "name". The next line outputs a message asking the user, in a sentence, what their name is. The line after that is where the magic comes in, and the user gets to manually type in their name. The redirection symbols are used just like in cout, except in cin the redirection symbols face the opposite way. In output they face left, in input they face right. See how nicely it makes sense? Anyway, the redirection symbols point to the variable that what the user types gets stored in. So, when the user types something here, whatever they type in as their name is stored as the value of our "name" variable. In the next line, cout is used again to display a message to the user. If I type in Josh as my name, it would output the message "Why hello there, Josh!" on the screen. You can see how this is done simply by looking at the code. Keep in mind that you need redirection symbols before each piece of text you are outputting, whether it be a "Hello" message in quotes or a variable's value, such as our name variable. Now we've gone over both input and output. Now here's an example asking the user what their age is:

#include <iostream.h>

int main()
{

int age; cout << "Please enter your age: ";
cin >> age;
cout << "You are " << age << " years old!";
return 0;
}


As you can see, int values can also be inputted! As we know, int is an integer variable type. There are other ways of creating strings, such as arrays. Arrays are a bit too advanced to discuss at this lesson, so in the meantime, read on to the next lesson! Contents - Next Lesson
Site hosted by Angelfire.com: Build your free website today!