Previously, on hercles:
Anyway. You can download the function.cpp, the main.cpp and the header file here. To get it to run, create a new project, and add those files to the project folder. Then, inside Code::Blocks, right click on the project and select ‘Add files…’. Do so, and you can compile, build and run it.
Quick explanation of the code: the use of a ‘while’ loop for the structure flow was discussed back in part 3 (yonder), so I haven’t actually done anything fancy here:
The only new concept is the ‘switch’ statement. It’s pretty simple. At the top of main, we declared something called userchoice, which gets an input (cin >> userchoice) from the user after being shown the function options. Switch takes the input, and performs a different operation depending on what that input is. Here, we say cout << [the answer returned by calling the desired function using the inputted values of n1, n2, thresh]. Like I said, simple.
At the end of the function is a little trick. If you’re running this from a compiler, it’s not necessary, ’cause the compiler keeps the window open after the function is run. If it’s a stand alone .exe executable, it closes immediately after the program finishes running the code. So cin.ignore() is used to clear the stream of data already inputted. Then cin.get() just waits for any kind of input from the user. Put these together with ‘press ENTER to quit’ and that effectively happens. Sorted.
Oh, and the only other new detail is using \n (newline) inside quote marks, instead of endl. Apparently that’s better, because endl clears the input stream and then adds \n. So unless you need to clear the stream, you might as well use \n because it’s less effort and more efficient.
And that’s it. That’s the core concepts for simple stuff. There’s also intimidating sounding things like templates and classes and whathaveyou, but I haven’t encountered them yet, so we’ll get to them when we get to them. You’ve got enough to fiddle around with and make a start though. Unless we’re dealing with major new concepts, these posts should be increasingly straightforward. Sorry about the pace so far, but when you start from scratch, the first posts are going to have to cover a lot of things in detail. Anyway we’ll see how it goes.
I’d end with a thematically appropriate pop-cultural series/season finale joke, but I don’t wanna risk it. No one likes big dumb spoilers.