Basic input/output

Here is a snippet that reads two string variables from the console, and writes them out. Not much to write home about… Explanation follows.


#include <iostream>
#include <string>

using namespace std;

int main(){

string fname, lname;
cout << "Enter first name: ";
cin >> fname;
cout << "Enter lastname: ";
cin >> lname;

cout << "Hello " << fname << " " << lname << endl;

return 0;

}

Now what goes on here? First, the #include directives tells the compiler what parts of code to include that does not reside in the file itself. In this example we use components from the c++ standard library, that comes with every decent compiler. More about this stuff later.
The “using namespace std” thing is a way to avoid typing more than necessary. cout for example belongs to the iostreams part of the standard library we included. So if we did not define “using namespace std”, we must have written std::cout instead, and who wants to do that?

cout prints stuff, cin gets stuff. The << and >> is a logical way to visualize what direction each of them takes. cin >> “put this inside”. cout << “puke this out”.

C++ itself does not have a variable type for strings, so we have to include the <string> from the standard library as well, so the compiler knows what a string actually is.

Think of the standard library as a (big) collection of pre-coded utilities, that you can include, and use in your own programs, so you don’t have to figure out how to actually make wheels. It’s done.

main() is the starting point for every program, so to compile one, you have to put some code inside this “block”, surrounded by curly braces.
It is common to return a value from main, so that if all is well, 0 is returned. therefore when defining main(), like when defining variables, a datatype is required. So int main(), means that main() will return an int, in this case (and most others) the int 0. The word “return” is a keyword, that is reserved for the purpose of just that. To return something, when the statement is reached.

So this snippet defines two string variables, prints something, gets some input, and prints out some more.

Leave a Reply