-4

Okay so still new to the syntax of the C++ programming language and have come across a few things that are shown in examples but don't quite explain things on a level for someone to fully understand what it is.

For example if you were going to create a variable say : int x = 0; what does the zero part do, sets it to zero or holds a false value? Particullary in the code below. Also some explanation on : if (!(cin>> input)) input = 0 if (!(cin>> 0)? if its not zero? seems like zero holds some other value.

Also cin.clear() and cin.ignore sure i've heard it clears the next line or erases something but really a thorough explanation of whats going on with this would really help? Can't really move on to bigger things if this simply parts has holes in it. Two other things is the endl function and cin.get() what do these do as well?

int main()
{
    int input = 0;

    do
    {
        cout<<"Enter a number (-1 = QUIT):";

        if (!(cin>> input))
        {
            cout<<"INVALID" <<endl;
            cin.clear();
            cin.ignore(10000, '\n');
        }

        if (input != -1)
        {
            cout<<input<<" was entered"<<endl;
        }
    }
    while (input != -1);
    cout<<"Done"<<endl;
    cin.get();

    return 0;

}
4
  • 3
    Why did you post five questions here? One question per question, please. You should really read your C++ book. Mar 16, 2014 at 21:59
  • 1
    Strong book recommendation: Stroustrup: Programming -- Principles and Practice Using C++. It will explain these questions ... and many, many more. To answer your question: int x = 0; assigns the value "0" to the variable "x". The value zero can mean "integer zero", or "boolean false" ... or can even be cast to a "null pointer". Among other things.
    – paulsm4
    Mar 16, 2014 at 22:00
  • You need a book, not a question here. -1
    – user207421
    Mar 16, 2014 at 23:32
  • because you can only post every 20 mins so it would just be worthless to do it split up. And yes a book could explain but the reason someone would post something like this is because they don't have one atm. So it might be smart to use your head before making comments on someones post Mar 18, 2014 at 5:48

1 Answer 1

1

The code below is the code provided in the question as I write this, except I've added the requisite headers and using directive at the top:

#include <iostream>
using namespace std;

int main()
{
    int input = 0;

    do
    {
        cout<<"Enter a number (-1 = QUIT):";

        if (!(cin>> input))
        {
            cout<<"INVALID" <<endl;
            cin.clear();
            cin.ignore(10000, '\n');
        }

        if (input != -1)
        {
            cout<<input<<" was entered"<<endl;
        }
    }
    while (input != -1);
    cout<<"Done"<<endl;
    cin.get();

    return 0;
}

#include <iostream>

is a preprocessor directive. The source code preprocessor is run before the compiler proper, and performs text substitution, text inclusion and text selection. The #include directs it to include all the text from a header called iostream. The angle brackets, as opposed to double-quote characters, says that it shouldn't bother to search in the including file's directory. Well actually it's unspecified what extra search it shouldn't do, but in practice, with current compilers, it's as described.

The iostream header provides declarations of i/o stuff from the standard library, such as std::cout.


using namespace std;

makes the identifiers from the std namespace available directly in the global namespace. Meaning you can write, for example, just cout instead of qualified std::cout or fully qualified ::std::cout.

A using namespace directive is practical for small exploratory and personal tool programs, but can be more troublesome in larger code base.

Anyway, remember to NEVER put such directive in the global namespace in a header, because that's a sure way to create name collisions in code that includes that header. As an example, the standard library defines a name std::distance. Without the qualification, with a using namespace std; directive, the name distance is very likely to collide with a name distance in using code.


int main()

is the minimal declaration of main. The main function was the user-provided startup function in C, and in C++ it serves roughly the same purpose, except that in C++ dynamic initialization of static variables can happen before main is executed.

The declaration above is the C++03 way. In C++11 it can alternatively be declared as

auto main() -> int

which means exactly the same, and which is a bit more verbose, but can be reasonable to indicate a convention of using this syntax in general. I.e. for consistency.

The main function can also have arguments, which then represent the command line arguments provided to the process, but this scheme only works well in UTF-8 based *nix-es. For the main arguments are char-based, and the default char-based text encoding in Windows is such that e.g. filenames with international characters can't be represented. Thus, it's not a generally good idea to use the main arguments for portable code.


    int input = 0;

declares a variable called input, of type int, and initializes it to 0.

Any zero value of a fundamental type represents false when it's used as a boolean. Conversely, any non-zero value represents true, and this convention stems from early C, which didn't have a bool type. In modern C++ it's better to use the bool type for booleans, with the values (literally) false and true.

The variable above, however, is not used as a boolean, but represents the last number input by the user.


    do
    {
        // Stuff, called the "loop body".
    }
    while (input != -1);

This is a do-while loop. The continuation condition stated after the while is checked after each iteration. Which means that the loop body is guaranteed to be executed at least once.

C++ has three other loops: the while loop; the ordinary for-loop, which collects all the loop control stuff in the loop head; and the range-based for, which is especially nice for iterating over the items in a collection.


        cout<<"Enter a number (-1 = QUIT):";

        if (!(cin>> input))
        {
            cout<<"INVALID" <<endl;
            cin.clear();
            cin.ignore(10000, '\n');
        }

The first statement above just prompts the user. The cout and cin streams are synchronized, so that when the subsequent input operation is attempted, the output, if not already presented on the screen, is flushed. Instead of such automatic, implicit flushing, you can guarantee a flush by doing it explicitly, like this:

        cout<<"Enter a number (-1 = QUIT):" << flush;

The expression cin >> input

  • attempts to interpret the next "word" of user input as an integer, and store that in the variable input, and

  • produces a reference to cin as its expression result.

If the input of text fails, or if the conversion from textual specification to int fails, then cin enters a failure state. In this state further input is just ignored. Happily that's easy to check for, because when a stream is used directly as an if or while (including do-while) condition, then it converts implicitly to boolean as if you had written !stream.fail().

Hence, !(cin >> input) does all of the above, and produces the result of !!cin.fail() (twice negated, “not not”), where fail is a member function that check whether the stream is in a failure state.

If the stream is in a failure state, then that state must be cleared, lest further input operations will all be ignored, and that's what

            cin.clear();

achieves.

In addition there will be some input text – at the least a newline (end of line marker) – left in the input buffer, and to avoid that text being processed as valid input the next time around the loop, it should better be removed! And that's what the

        cin.ignore(10000, '\n');

accomplished. Under the assumption that there's not more than 10000 characters left in the input buffer…


            cout<<"INVALID" <<endl;

Outputs the text “INVALID” followed by a newline. Outputting the endl manipulator has the effect of a newline plus a flush. Thus the above is equivalent to and just short for

            cout<<"INVALID\n" << flush;

It often happens that newbies are concerned with the lack of efficiency of endl as opposed to just \n. This concern is however misplaced. Iostreams are for convenience and (due to stronger type checking) avoiding the easy bugs of C style i/o; they're generally not what one would choose for efficiency.


After the loop, the

    cout<<"Done"<<endl;
    cin.get();

stops the program until the user enters some input.

This is because when the program is run from an IDE (as opposed to from the command line), the console window could just otherwise disappear. And especially for non-interactive programs that's undesirable. So the statement above, while not needed for this particular program, is a general convention.

However, it's ungood. It becomes very annoying when the program is run from the command line! Instead, to see all the output of a program, do either

  • run it from the command line, or

  • run it in a way that automatically stops at the end (e.g. Ctrl+F5 in Visual Studio), or

  • place a breakpoint at the last } right curly brace of main, and run it in the debugger.


    return 0;

is unnecessary, since this is the default function result for main (main is unique in having a default function result).

The value returned from main will in practice become a process exit code.

In both Windows and *nix the convention is that 0 means success and any other value means failure.

In C++ the only portable values are 0, EXIT_FAILURE and EXIT_SUCCESS, where the latter two come from the stdlib.h header. EXIT_FAILURE and EXIT_SUCCESS depend on the system at hand, but the latter is typically just 0. In Windows you may want to use Windows' own E_FAIL instead of EXIT_FAILURE, because (for unfathomable reasons) Windows C++ compilers typically define EXIT_FAILURE as 1, which is also a specific Windows error code – and in Windows the process exit code is typically literally what that term indicates, namely a standard error code, with 0 as “no error”.

Not the answer you're looking for? Browse other questions tagged or ask your own question.