C++ Visual Studio : Debug Assertion Failed! Expression: c >= -1 && c <= 255 - c++

I'm trying to do a basic C++ score / grade system. I want to validate the users input. If the data is not a number, I want it to display an error message. If it is, I want it to carry on.
However, if the user enters a letter, say for example 'a' or 'A'. It spits out this error :
Debug Assertion Failed!
Program:
...ers\Alex\source\repos\worksheet_1.2a\Debug\worksheet_1.2a.exe
File: minkernel\crts\ucrt\appcrt\convert\isctype.cpp
Line: 36
Expression: c >= -1 && c <= 255
This is the code:
#include "stdafx.h"
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
int score;
// Recieve user input of score between 0-100. Stores input in score var
cout << "\nWhat score did you get?\n" << endl;
cin >> score;
// Validating input
if (!isdigit(score)) {
if (score <= 59)
cout << "Your grade is F" << endl;
else if (score > 59 && score < 70)
cout << "Your grade is D" << endl;
else if (score > 69 && score < 80)
cout << "Your grade is C" << endl;
else if (score > 79 && score < 90)
cout << "Your grade is B" << endl;
else if (score > 89)
cout << "Your grade is A" << endl;
}
else {
cout << "Sorry, that is not a number. Please try again." << endl;
}
return 0;
}
It works fine if a number is entered, but not at all if a letter is.
I have looked at several other answers and videos based on 'Debug Assertion Failed' but cannot find one for this particular error.
Thanks for reading and help given!

It is rather strange that isdigit takes an int not a char, because thats what it is for (from here, emphazise mine):
Checks if the given character is one of the 10 decimal digits:
0123456789.
The behavior is undefined if the value of ch is not representable as
unsigned char and is not equal to EOF.
Seems like isdigit is quite some trap and you were lucky to get assertion fired. Anyhow, even though it takes an int you should pass a char:
std::string s = "12asbc";
std::cout << isdigit(s[0]); // prints 1
std::cout << isdigit(s[3]); // prints 0
Anyhow your check isnt that meaningful. If it worked as you expected, you would only know that the number isnt a single digit, but your code would still fail if the user entered abcd or anything that is not a number. To check if the input was correct, you could do
int score;
if (std::cin >> score && 0 <= score && score <= 100) {
// ok input
} else {
// invalid input
}

why did you type !isdigit(score) instead of isdigit(score)?
Don't put ! in front of isdigit(score).
isdigit() returns True when the argument is number.

Related

GPA rater in C++

I'm trying to code a GPA rater.
The problem:
Write a C++ program that asks the user for their cumulative GPA in the range [0,4]. If the GPAenter code here
is in:
[3-4] you say, “Superb!”
[2-3[ you say, “Good!”
[1-2[ you say, “Hmm!”
[0-1[ you say, “No comment!”
The program should display an error message and exit if the GPA entered exceeds 4 or less than
0.
Code:
#include <iostream>
using namespace std;
int main()
{
double grade;
cout << "Input your GPA: ";
cin >> grade;
cout << endl << endl;
if (grade >= 0 && grade <= 4)
{
if (grade >= 0 && grade <= 1)
{
cout << "No comment!";
}
if (grade >= 1 && grade <= 2)
{
cout << "Hmm!";
}
if (grade >= 2 && grade <= 3)
{
cout << "Good!";
}
if (grade >= 3 && grade <= 4)
{
cout << "Superb!";
}
}
else
{
cout << "Error : GPA is not in the specified range";
}
return 0;
}
I feel there is a more efficient way than mine.
Is there?
Thanks in advance
There's probably a way to code golf it, but your code is clear. It does check things that you already know more than once.
For example, if (grade >= 0), then it still is on the next line. If it's not <= 1, then it is definitely > 1 -- you only need to check if it's <= 2 (with else if).
If you want to make something silly, you could something like this (after checking if grade is in range):
string m[4] = {"No comment!", "Hmm!", "Good!", "Superb!"};
cout << m[min(3, int(grade))];
You need to add:
#include <cmath>
#include <string>
It's fewer lines of code, but possibly not more efficient (you need to measure)

while loop w/ 2 conditions does not work c++

I'm working on a minigame in C++ lately. The goal is to write a little game where you have to guesse a number. If you do so you'll get a point (I call it hit there) and if you don't you'll get a "miss". Logically speaking I don't want the game to go for ever. So I was trying to use a while loop to define at which scores you can still play. How you will be able to see in the code there are two conditions. Here is why I asked you: As long as there are two conditions it just ignores these so the game turns into an endless game. I don't recive any error-messages from VS2019. When I only try it w/ one condition it works just fine.
Here's the code:
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
cout << "Welcom to the Hit-or-Miss-minigame. Here are the rules:" << endl;
cout << "You have to guess the same number as the computer. The numbers are within 0 and 10(both are still included)." << endl;
cout << "If you do so, you'll get a 'HIT' but if you don't you'll get a 'MISS'. When you reach 10 'HIT's you win" << endl;
cout << "but if you get a 'MISS' 15 times you'll lose." << endl;
char rep = 'y';
while (rep == 'y')
{
int hits = 0;
int miss = 0;
while ((hits < 3||miss < 15)) //Somehow doesn't work. So why?
{
int input_number;
srand(time(NULL));
int random_number = rand() % 11;
cout << "Your number: ";
cin >> input_number;
if (input_number == random_number)
{
cout << "HIT" << endl;
hits += 1;
}
else if (input_number != random_number)
{
cout << "MISS" << endl;
miss += 1;
}
else if ((input_number > 10) || (input_number < 0))
{
cout << "That was not an option";
}
else
{
cout << "That's not supposed to happen." << endl;
}
}
if (hits == 10)
{
cout << "You've won! Do you want to play another round?(y/n)" << endl;
cin >> rep;
}
else if (miss == 15)
{
cout << "You lose! Do you want to play another round?(y/n)" << endl;
cin >> rep;
}
}
}
I really would appreciate any help. Thanks!
EDIT: Problem solved. THANK YOU GUYS!
if you want the game will end after 3 hits or 15 misses you should use the && operator and not the || operator
it is because the || operator will return true when at least one of the conditions true, the && operator will return true when both of the true
Like the other comment said you should use && in your while loop, because you can have 16 misses and 3 hits before the loop breaks(for example 2 < 3 || 25 < 15 returns true and is only false when you get 3 < 3 || 25 < 15), which won't enter any if below the while, and it will just reset the variables back to 0 (this makes the while infinite). Furthermore if you put && in the while you need to change the if statement for hits to hits == 3 or it will never happen.
Also as a side note your if statement for numbers below zero and bigger than 10 needs to be above the one where you check if the guessed number is a miss (because every number bigger than 10 and smaller than 0 is a miss).
Hope this helps

How do I prevent program from running BOTH an IF and ELSE statement with C++?

#include <iostream>
#include <string>
int main()
{
int hun;
std::cout << "Please pick a number between 1 and 100 \n";
std::cin >> hun;
if (hun > 50)
{
std::cout << "Your number is greater than 50. ";
}
if (hun < 50)
{
std::cout << "Your number is less than 50. ";
}
if (hun > 100)
{
std::cout << "Pick a number LESS than 100. ";
}
else { std::cout << "Your number is equal to 50. "; }
return 0;
}
If I run it without the:
std::cout << "Pick a number LESS than 100. ";
then the program works as expected. However it doesn't work if I include it. For example if I input "13" I get both the message "Your number is less than 50, AND your number is equal to 50" ?? I don't understand why it is still executing the else statement if my IF statement was already met. This isn't an issue ONLY if I removes that 3rd IF statement.
I cannot figure out why it is just that line that is messing up. I seem to have everything written correctly, and I didn't forget the curly brackets. So why is this happening?
I'm sure it's a simple mistake. It's my first week coding and I'm doing it on my own with no outside help, so I don't have anyone to go to for silly questions like this.
While I'm here, how do I get the program to say something like "You have entered an invalid response. " When the user inputs a word or a letter? I thought about doing something like:
int word;
word = 1-100;
if (hun = word) or (hun != int?)
(But that will only subtract 100 from 1 giving me -99 and not the range, I really do not even know where to begin with this)
You need to implement if-else if- else statements:
if (hun > 100)
{
std::cout << "Pick a number LESS than 100. ";
}
else if (hun > 50)
{
std::cout << "Your number is greater than 50. ";
}
else if (hun < 50)
{
std::cout << "Your number is less than 50. ";
}
else
{
std::cout << "Your number is equal to 50. ";
}
The reason why the original code didn't work is that the else was only linked to the last if. So if a number satisfied one of the earlier if statements but not the last if it would go to both the if it satisfied and the else as the last if was not satisfied.
Additionally you must reorder it so that the more extreme cases are first. Otherwise if hun is more that one hundred but you have the condition hun > 50 then it will go to that if-else and then skip the rest.
Try this
if (hun >= 0 && hun < 50){
std::cout << "Your number is less than 50. ";
}
else if (hun == 50){
std::cout << "Your number is equal to 50. ";
}
if (hun > 50 && hun <= 100) {
std::cout << "Your number is less than 50. ";
}
else {
std::cout << "you ve entered invalid number " << hun << " . supported range is [0 - 100]";
}

Unexpected output in cout [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So, this is my very first questions on Stack Overflow. I'm in the process of learning C++ after some hard-fought experience with MATLAB. I've got a simple exercise that builds fine, but does not produce the expected result.
I get no errors, either. I'm running Xcode 5.
I suspect the problem has something to do with the initialization of my variables. When I look into debugging, my variables stay set to 0.
#include <iostream>
using namespace std;
int main()
{
//Declare variables
int score = 0;
//input score
cout << "Emter score: ";
cin >> score;
if (score == 100)
{
cout << "Final Score: " << score;
cout << "You received a perfect score! \n";
// 100% is an A.
}
else if ((score >= 90) && (score <= 100))
{
cout << "Final Score: " << score;
cout << "Your grade is an A. Nice Job! \n";
// 90-100 is an A.
}
else if ((score >= 80) && (score <= 89))
{
cout << "Final Score: " << score;
cout << "Your grade is a B. Well done. \n";
// 80-89 is a B.
}
else if ((score >= 70) && (score <= 79))
{
cout << "Final Score: " << score;
cout << "Your grade is a C. Really? \n";
// 70-79 is a C.
}
else if ((score >= 60) && (score <= 69))
{
cout << "Final Score: " <<score;
cout << "Your grade is a D. You suck. Seriously. \n";
// 60-69 is a D.
}
else if ((score >= 0) && (score <= 59))
{
cout << "Final Score: " << score;
cout << "You got an F! YOU FAIL! GO JUMP OUT THE WINDOW. \n";
// 0-59 is an F.
}
return 0;
}
Sorry for the long post, I did not want to leave anything out. Thanks again.
ETA: Fixed the newline characters. I retyped the code in line for line and it ran just fine. I suspect it had something to do with the way all this stuff was being cast, but I'm not sure.
Welcome to SO, and to C++!
This issue may all come down to a simple typo - where you've used the newline character, you've typed a forward (instead of back-) slash; the correct newline character is \n.
There is actually another method for outputting the newline character as follows:
cout << endl;
which is the method I would recommend, at least for now, while you have no reason to choose one over the other. Others disagree however, and would advocate the use of \n. The difference between the two is that endl performs a flush, while \n does not (and /n certainly does not!) - at least not as standard.
If all this flush talk sounds like I've gone potty - just ignore it, stick to endl (unless you're on a course where your instructor has specified to use \n), and you'll no doubt encounter more about buffers and flushing soon!
Assuming your "unexpected output" was "everything is on the same line and it says '/n' everywhere" - this is all you need do to fix (you can go ahead and remove those '/n's).
NB: The reason for /n vs \n is that \ is the escape character - that is, whatever follows it is said to be escaped. Thus in the newline character, \n, n is escaped, and we do not see an 'n' displayed in cout.
But that does not mean that the n is not important! Together with \ it forms a single ASCII character (single will be important later, when you begin manipulating variables of the char type) to print a new line. Conversely, / is not the escape character, so when you used /n you saw both / and n displayed.
I cleaned up your code some and made note of some common practices that may be helpful to know. Also, as the previous answer mentioned the most likely cause of your problem was the newline character. Welcome the wonderful world of c++!
include
using namespace std;
int main()
{
//Declare variables
double score = 0; //this should really be a double if we are talking about grades
//input score
cout << "Enter score: ";
cin >> score;
cout << "Final Score: " << score << endl; //endl is the more common line ending that I've seen
// with my experience in C++
cout << "Your grade is a"; //you can remove all commonalities between if
// statements to save yourself some typing
// This is also common practice
if (score == 100)
{
cout << " perfect score!" << endl;
// 100% is an A.
}
else if (score >= 90 && score < 100) //we use < 100 instead of <= 99 because what about
// numbers between 99 and 100
{
cout << "n A. Nice Job!" << endl;
// 90-100 is an A.
}
else if (score >= 80 && score < 90)
{
cout << " B. Well done." << endl;
// 80-89 is a B.
}
else if (score >= 70 && score < 80)
{
cout << " C. Really?" << endl;
// 70-79 is a C.
}
else if (score >= 60 && score < 70)
{
cout << " D. You suck. Seriously." << endl;
// 60-69 is a D.
}
else //if we are not handling errors (assuming user
// enters 0 to 100), we can just say else
{
cout << "n F! YOU FAIL! GO JUMP OUT THE WINDOW." << endl;
// 0-59 is an F.
}
return 0;
}

How do I stop a certain part of a program using the user's input?

I'm making a program that tallies grades. I want to know how to stop a certain part of a program based on the user's input. Below is the program I am working on. How do I stop the program if the user enters "done"? Also, I don't necessarily have to use "done" to exit the program. I was initially going to use -1, but I ran into a problem where I had to make a robust program where values < 0 and > 100 are not accepted.
int grade;
a=b=c=d=f=0;
do
{
cout << "Enter a grade or enter done to stop. ";
if (grade >= 90 && grade <= 100)
{a++;}
if (grade >= 80 && grade < 90)
{b++;}
if (grade >= 70 && grade < 80)
{c++;}
if (grade >= 60 && grade < 70)
{d++;}
if (grade >= 0 && grade < 60)
{f++;}
} while (grade != 'done');
just do a return 0? Also, you can't do grade = 'done', unless you overrode the = operator or something.
The most simple way to ask user to enter integer value, which is out of range of values you expected him to enter (ex. -1). "when done - enter -1".
Also if(grade = 'done') - assignement is here, to compare use operator==, which is
// if(grade == 'done')
or you can use the following approach:
do
{
cout << "Enter a grade or enter done to stop. ";
// first try to get string from user (which he/she enters when done)
string str;
cin >> str;
if (str == "done") // if done was entered - exit from the loop
break;
// else clear fail bit in stream object and read int value
cin.clear();
cin >> grade;
if (grade >= 90 && grade <= 100)
{//a++;}
if (grade >= 80 && grade < 90)
{//b++;}
if (grade >= 70 && grade < 80)
{//c++;}
if (grade >= 60 && grade < 70)
{//d++;}
if (grade >= 0 && grade < 60)
{//f++;}
} while (grade != 'done');
Firstly, "grade" is type int, so you can not convert int to *char, if you want that "grade" is int than you can exit with -1. Or if you want to exit with "done", than grade can be char[5], and you can use atoi() to convert string to integer to check, and strcmp() to compere "grade" with "done".
You have write code to enter a string. You can then test if the string equals "done". If it doesn't you then convert the string to an integer, then you can check against your grade boundaries.
If you really want to use numbers AND strings i suggest using stringstreams. Here is an example:
string Text = "456";//string containing the number
int Result;//number which will contain the result
stringstream convert(Text); // stringstream used for the conversion initialized with the contents of Text
if ( !(convert >> Result) )//give the value to Result using the characters in the string
Result = 0;//if that fails set Result to 0
//Result now equal to 456
Source link
First of all, single quotes denote a character literal, double quotes a null terminated string (2.14 or so).
if(grade = 'done') will always be true, compiler should have thrown a warning at you that you aren't doing what you think you are doing, you're assigning it then checking if it is true, which it will always be.
And you're trying to assign an integer to a string.
This seems like homework so i won't write it, but you need to take in a string from stdin, then parse it, e.g is it an integer or string, the act on that data. to terminate you can call exit, break from the loop or return from the function.
You can take the inputs as string, if the first character is not a digit then break the loop, covert the string to integer otherwise:
#include<iostream>
#include<string>
#include<cctype>
#include<cstdlib>
using namespace std;
int main() {
int grade;
string input;
int a, b, c, d, f;
a=b=c=d=f=0;
do
{
cout << "Enter a grade or enter done to stop: ";
cin >> input;
cout << endl;
if(!isdigit(input[0])) {
break;
} else {
grade = atoi(input.c_str());
}
if (grade >= 90 && grade <= 100)
{a++;}
if (grade >= 80 && grade < 90)
{b++;}
if (grade >= 70 && grade < 80)
{c++;}
if (grade >= 60 && grade < 70)
{d++;}
if (grade >= 0 && grade < 60)
{f++;}
} while (1==1);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "d = " << d << endl;
cout << "f = " << f << endl;
getchar();
return 0;
}