I have a task to make a program that will calculate two numbers put into it.
And also show the calculation between every number.
And if I input a letter not a number the program crashes, this is an more advanced task that I dont need to do but I really want to know how to do this. So that is my question, how do I make the program give me a warning that not to use letters and still give u ability to input numbers if you enter a letter, instead of crashing.
This is how my code looks so far
Blockquote
float nmr1, nmr2;
cout << "Write two numbers.\n";
cin >> nmr1;
cin >> nmr2;
cout << "\n";
cout << nmr1 << " + " << nmr2 << " = " << nmr1 + nmr2 << endl;
cout << nmr1 << " - " << nmr2 << " = " << nmr1 - nmr2 << endl;
cout << nmr1 << " * " << nmr2 << " = " << nmr1 * nmr2 << endl;
cout << nmr1 << " / " << nmr2 << " = " << nmr1 / nmr2 << endl;
cin.get();
cin.get();
return 0;
maybe there are easier things to write but I'm a beginner, and I would use the search tool but I don't know what to search.
cin >> var_of_type_float will return false if the input fails. So simply use that in a conditional expression, something like:
if (cin >> nmr1) { // all ok
If you want to check the input, usual way is to read a string, check if there are non valid character, then parse it into a number (tedious task in C++ with real numbers) and store in a float, finally, perform operations with those floats.
If you are not working with text input yet, I recommend you to wait to implement this feature, as it could be complex for a beginner in programming
To check if a bad input was received via cin you use the following condition:
if(!cin){
// bad input was received, don't use cin again.
}
What really crashes is the divide-by-zero operation.
If invalid number is entered, nmr1 and nmr2 will be 0
and nmr1/nmr2 will crash. You must check for (nmr2 != 0) before attempting to divide.
Related
I'm reading one of my textbooks that does a poor job of explaining the code it introduces. Here the sample code:
int choice;
QString response;
do {
cout << READ << ". Read data from a file.\n"
<< ADD << ". Add items to the Library.\n"
<< FIND << ". Find and display an item.\n"
<< REMOVE << ". Remove an item from the Library.\n"
<< SAVE << ". Save the Library list to a file.\n"
<< LIST << ". Brief listing of Library items.\n"
<< QUIT << ". Exit from this program.\n"
<< "Your choice: " << flush;
response = cin.readLine();
choice = response.toInt();
} while(choice < READ or choice > QUIT)
According to the QT Documentation,
Returns 0 if the conversion fails.
That means, if string is not numeric, it will return 0.
I am trying to compare two strings for a trivia program, one entered by a user and the other accessed from a node. The comparison is within an IF statement and always returns false. Below is the code used for this function. Both variables userAnswer and answer are of the type string.
cout << "Question: " << cur_ptr->question << endl;
cout << "Answer: ";
getline(cin, userAnswer);
if (userAnswer == cur_ptr->answer) {
cout << "Your answer is correct. You receive " << cur_ptr->points << " points." << endl;
totalPoints += cur_ptr->points;
}
else {
cout << "Your answer is wrong. The correct answer is: " << cur_ptr->answer << endl;
}
cout << "Your total points: " << totalPoints << endl << endl;
cur_ptr = cur_ptr->next;
Whenever my program runs, it generates an output like so
Question: How long was the shortest war on Record? (Hint: how many minutes)?
Answer: 38
Your answer is wrong. The correct answer is: 38
Your total points: 0
getline(cin, userAnswer) is keeping the \n. You might consider trimming the string with something like the following
getline(cin, userAnswer);
userAnswer.erase(userAnswer.find_last_not_of("\n\r") + 1);
No guarantees that this is the answer, but I've run across this a few times and it's just been a trailing \n or \r.
Do some boost::trim() on the strings to compare, before the comparison, and see if that helps.
In 2010 Visual C++ Express, I'm using
...
ifstream inFile("inputfile.dat");
double number;
while(inFile >> number)
{
cout << number << endl;
}
...to read 8 numbers stored in a file into the program, and show them on the monitor. It shows them all correctly and as needed, but I need to store each individual number as already specified doubles. From top to bottom,
Customer 1's Identification #
Balance
Payments outstanding
Purchases that have been made
then the other 4 numbers are the same thing just for a different customer. I've tried a ton of different ways to do it, but each come with:
"Run-Time Check Failure #3 - The variable 'variableName' is
being used without being initialized."
and it happens with almost all of the variables. I've searched for anything to help me with this but couldn't seem to find something that would help me to the extent of what I needed.
Assuming that you really want to store these in 8 distinct variables, and not in some aggregate data type:
std::ifstream inFile("inputfile.dat");
double number;
if(inFile >> cust1id >> cust1bal >> cust1pay >> cust1purch >>
cust2id >> cust2bal >> cust2pay >> cust2purch) {
std::cout <<
"Customer 1's Identification #: " << cust1id << "\n" <<
"Balance: " < cust1bal << "\n" <<
"Payments outstanding: " << cust1pay << "\n" <<
"Purchases that have been made: " << cust1purch <<
"Customer 2's Identification #: " << cust2id << "\n" <<
"Balance: " < cust2bal << "\n" <<
"Payments outstanding: " << cust2pay << "\n" <<
"Purchases that have been made: " << cust2purch << "\n";
}
working on one of my first programming assignments, a text to morse (and back) convertor, but for whatever reason when I introduce a piece of text with a space between words my programme goes into an endless loop and crashes. Any ideas? Sorry if this description sucks, still getting my head around programming lingo.
this is the piece of the program that isn't functioning properly:
{
string user_input;
cout << "----------------------------------------" <<endl
<< "Text to Morse Mode" << endl
<< "Enter text for conversion : "<<endl;
cin >> user_input;
cout << endl << endl << user_input << " converts to : ";
unsigned int str_lenght;
str_lenght=user_input.size();
cout << endl;
for (i=0;i<str_lenght;i++)
{
find_string=0;
while (find_string < stop_string)
{
if (user_input[i]==text[find_string][0])
{
count=1;
cout << morse[find_string] << " ";
break;
}
find_string = find_string+1;
}
}
cout << endl << endl << endl;
if (count==0)
cout << endl << " an error was encountered " << "\a" << endl ;
}
stop_string isn't defined anywhere from what I see. In order to break the loop via incrementing you need to define stop_string. Also find_string = find_string+1; could be shortened to find_string++
First you haven't defined stop_string variable anywhere. First define it or use another variable. If it is string length intent to use here, use the str_length you have created.
Secondly if you want to input spaces in between your words, use getline instead of cin. cin delimits space character.
Here is an excerpt of my code, where the problem lies.
long long user_largest_plus;
long long user_largest_minus;
cout << "Input the largest+1 in decimal: " << endl;
cin >> user_largest_plus;
//cout << endl;
// cout << "Input the largest-1 in decimal: " << endl;
cin >> user_largest_minus;
cout << endl;
cout << "In decimal plus: " << user_largest_plus;
cout << endl;
cout << "In decimal minus: " << user_largest_minus;
As soon as I input 9223372036854775808 to user_largest_plus, the execution would terminate. That is, I wouldn't be able to input for user_largest_minus.
I am using Code::Blocks, MinGW compiler.
Is it because I just overflowed the variable, and the error triggered this termination. Any work around?
By the way, that number is 2^63 - 1, maximum number that I can store.
Thanks
Try replacing
cin >> user_largest_plus;
with
if( !( cin >> user_largest_plus ) ) {
user_largest_plus = 0;
cin.clear();
cout << "Bad input. Using zero instead\n";
}
When the input text is not a valid long long, two interesting things happen:
user_largest_plus is never set, and
the bad bit is set in cin.
The provided code sets some value to user_largest_plus to avoid undefined behavior, and clears the bad bit, so cin can still be used.
Assuming it is because the entered number is to big (and to prevent bugs when the user enters APPLE as the size, you should do something like this:
string user_largest_plus_string;
long long user_largest_plus;
cout << "Input the largest+1 in decimal: " << endl;
cin >> user_largest_plus_string;
user_largest_plus = atoi(user_largest_plus_string.c_str());
if (user_largest_plus == 0)
throw std::runtime_error("User entered something besides a number!");
cout << "largest+1 is now " << user_largest_plus << "." << endl;