I am making a grade calculator for UCAS points, so I need the user to enter 18 grades for each unit - I've done that and it works. But If the users hasn't done one of the units they need to enter "NS". But in the console program when I enter two characters it skips the next input.
For example, if I didn't have a grade for unit 1: I enter "NS", but the program misses asking the input for unit 2 and then asks for unit 3 to be entered?
Here is the code that gets the users input for the units:
for(int i = 1; i <= 18; i++) // This for loop which get the grades for each of the 18 units
{
cout << "Enter grade for unit " << i << ": "; // Ask the user for each grade them received for their units
cin >> temp_grade; // Each value is put into a temporary value
if(tolower(temp_grade) == 'p')
{
Total_BTEC_Points = Total_BTEC_Points + p; // Each if statement will use the temp_grade variable to check what the user has entered and then add it to the total BTEC points variable
}
elseif(tolower(temp_grade) == 'm')
{
Total_BTEC_Points = Total_BTEC_Points + m;
}
elseif(tolower(temp_grade) == 'd')
{
Total_BTEC_Points = Total_BTEC_Points + d;
}
elseif(tolower(temp_grade) == 'ns')
{
Total_BTEC_Points = Total_BTEC_Points + 0;
}
}
Here is the code how the variable is declared: char temp_grade; // Temporary variable to hold the values for the 18 units
NS is not a character. It is 2 characters. So first time N is read, and it does not hit any ifs and do nothing. Second S is read and it doesn't hit any ifs too.
Next you are asked for your third character. All as expected.
'ns' is not a character either. It is multicharacter literal and have a type of int. Program compiles only because of some implicit conversion.
So either change ns to just n or find other way to read input.
P.S. Always compile on high warning level and get rid of all warnings. They are often indication of some elusive mistake.
For example, if I didn't have a grade for unit 1: I enter "NS", but the program misses asking the input for unit 2 and then asks for unit 3 to be entered?
This is because you are storing the input in a char variable which can only hold a single character. So when you enter two character as input (Let's say "NS") the N is put into the char variable and the 'S' stays in the input buffer. So when you start the loop a second time the std::cin statement is skipped because we already have something in the input buffer (The character 'S') so the next character from the buffer is then put into the char variable.
So remember a char variable can only hold a single character. If you think there is a possibility that you might need to hold more then one character at a time (Like "NS") you should instead use a std::string variable or a C style string.