Hello op10 and Cheddar99,
I will give this a try and hope I do not make any mistakes.
A line like:
cin >> nm;
is known as formatted input. This works best when the variable is defined as a numerical variable. The way this works is that the "std::cin" will read up to the first white space or new line (\n) whichever comes first. In the case of the "\n" it will leave this in the input buffer and move on to the next line of code. When the next
cin >> someVariable;
comes along having the new line in the input buffer is not a problem.
Your other option for input is, as you used,
getline(cin, name);
. The way this works is because you are reading what you type on the keyboard it will take everything, meaning spaces between words, and even the "\n" will be extracted from the input buffer, but is discarded and not used. Unlike the "std::cin" the "std::getline" will leave the input buffer empty.
The problem you run into is:
1 2 3
|
cin >> nm;
// <--- Followed by.
getline(cin, name);
|
The first statement will leave a "\n" in the input buffer and the second statement will take the "\n" from the input buffer and figure it is finished and move on to the next line.
In a case like this I try to follow the last "std::cin" with, as Cheddar99 suggested, with
std::cin.ignore(numeric_limits<streamsize>::max(),'\n');
. The use of
std::cin.clear();
is not always necessary unless something caused the stream to fail. You just need to clear the input buffer. Having the
std::cin.clear();
in the code does not hurt anything. It just may not be needed.
Earlier I said that
std::cin >> nm;
is formatted input that works best with numeric variables. I do not believe that "std::cin >>" actually can tell the difference between a short, int, long, float or double just that it is a numeric entry that is expected. So when you try to enter "a" into the variable "nm" it will cause the "cin" stream to fail. To check for this I most often use:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
cout << "Enter the students number :" << endl;
cin >> nm ;
while (!std::cin)
{
std::cout >> "\n Invalid entry. Try again.\n" << std::endl;
std::cin.clear(); // <-- to reset the state bits.
std::cin.ignore(numeric_limits<streamsize>::max(),'\n'); // <--- To clear the input buffer.
std::cout << " Enter the students number : ";
std::cin >> nm;
}
|
This way if anything other than a number is entered for "nm" it will stay in the while loop until a good number is entered. Otherwise you leave "std::cin" in a failed state and nothing else can be entered. This is one way of using the formatted input.
You can change the output on line 6 to whatever you need.
@Cheddar99,
Your use of the "using" statements is better than OP's choice, but since this is a small program I would put the "using" line inside main and keep the scope local because it is the only place that you use them. It is best if you can avoid putting anything other than classes, prototypes and structs in the global scope.
Hope that helps,
Andy