Whatever book/internet tutorial you're learning from right now, throw it away. No, seriously. This code reads as if it was written in 1992. Here is the list of books recommended by Stack Overflow community.
Also, if your Dev-C++ version is 4.9.9.2, I highly recommend an update - newer IDE will provide better editor, better debugger, and, (really important) better compiler. Better compiler will give you better error messages, and that is important when learning C++ (trust me on that, I know from experience) Common alternatives are: Visual C++, Code::Blocks or if you like Dev-C++, just upgrade to Orwell Dev-C++.
Let us fast forward to 2013 now.
Warnings
There are several jokes that can be reduced to "meh, i listen to errors not to warnings". They are wrong. 95% of warnings mean that the code is wrong. Since C++ is a tricky language, everyone should enable warnings in theirs IDEs (puzzles me why they are not enabled by default).
Headers
Introductions of namespaces to C++ means old headers are deprecated. This means they should not be used when writing new code.
The headers names are changed like this:
builtin C++ headers don't have ".h" at the end. ("iostream.h" --> "iostream")
Headers originated from C don't have ".h" at the end, also they are prefixed with "c" ("stdio.h" --> "cstdio")
conio.h is neither builtin C header nor builtin C++ header, so the name stays like it was.
Here is list of standard headers
Strings
C++ has a string type. std::string
. It allows for simple string operations without hassle. Just #include <string>
to use it.
string first_name = "John";
string surname = "Titor";
string full_name = first_name + " " + surname; //easy concatenation
//string a = "first" + " " + "name" //nasty surprise
string c = "first" + string(" ") + "name" //much better
//or using stringstream (#include <sstream>)
stringstream ss;
ss << "first" << " " << "name";
c = ss.str();
gets()
This function is impossible to use safely - it doesn't limit user input nor expands buffer. In your example code, someone could enter more than 120 characters and end up envoking undefined behaviour. This term is equivalent to math's undefined behaviour - anything can happen, including 1 being equal to 2. The gets()
function was recently removed from C language altogether.
C++ has a safe alternative.
string s;
getline(cin, s);
Proper declaration of main()
int main()
or
int main(int argc, char* argv[])