Sunday, July 18, 2010

C++: getting user input and storing it as a variable

So with the basics in variables at hand, now the question becomes, "how do
we even let users enter some values into it?" This is done with a small
change from output statement (the cout):
Ccin >> var;
Where "var" is your variable. As you might have noticed, the "cin" is
"console in", the operator (in iostream library) that allows us (the users)
to type something to a program (actually, a computer) so that the program
can work with our intput.

For example, suppose if I want my computer to tell me my name, I would first
declare a string variable called "my_name," then I would ask my computer to
ask me 9ironic, is it?) what my name is. The computer would take my name as
an input then display it back to me on the screen. Here's how it would look
like:
string my_name; // My name variable.
Ccout << "Hi, what is your name?" << endl;
Ccin >> my_name;
Ccout << "My name is " << my_name <, "." << endl;
As you have seen, we can indeed embed, or put in a variable as part of an
output statement. For example:
Computer: Hi, what is your name?
Me: types "Joseph".
Computer: My name is Joseph.
And that's what it would look like when we do run a program after compiling
it (compilers and how it works will be studied further much later). The
problem becomes when we want to store a line of text; fortunately, there is
a way of doing it via getline function (a function, in this sense is a mini
program that does whatever inside it to perform a task). Here's how it
looks:
Getline(cin, string_variable);
This essentially means that we want to get an entire line of text until we
press ENTER key (return, or new line). You'll meet more syntax like this
when we get into all sorts of discussion on functions later.

More to come later...

No comments:

Post a Comment