c++ segmentation fault (core dumped) with modulus - c++

I am working on a program that allows the user to practice division. My code is below:
//div1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
#define CLS "\033[2J\033[1;1H"
#define NEWLINE "\n"
int main() {
srand(time(NULL));
int a, div1, div2;
div1=rand()%11;
div2=rand()%11;
while (div2>div1) {
swap(div1,div2);
continue;
}
if (div1%div2!=0) {
return main();
} else {
cout << CLS;
cout << NEWLINE;
do {
cout << div1 << " / " << div2 << " = ?" << endl;
cin >> a;
cout << CLS;
cout << NEWLINE;
cout << "\t\tWrong!!" << endl;
cout << NEWLINE;
} while (a!=div1/div2);
cout << CLS;
cout << NEWLINE;
cout << "\t\tCorrect!!" << endl;
cout << NEWLINE;
cout << "Hit enter to continue." << endl;
cin.ignore();
cin.get();
return main();
}
return 0;
}
Basically, what it is supposed to do is first choose two random numbers. Then, it is supposed to check to see if the second number (div2) is greater than the first (div1), and if they are, it will switch them. Then, it will use the modulus (div1%div2) to make sure that the two numbers can be divided by each other without a remainder. If they cannot be divided without a remainder, it will restart the program (return main();). However, whenever I run it, I get the segmentation fault: core dumped, either when I start it or after running it a few times. Any ideas on how to fix this?
Thanks!!

Here's an example of what I've said in the comments. Obviously, you can refactor this so that it works more gracefully (as of now it'll give you floating point exceptions sometimes), but it gives you an idea on how to do this without calling main again.
NOTE: You do not need to make a constant for NEWLINE. There is already a built-in constant in std. In fact, you're already using that constant (endl). So you can just do cout << endl instead of cout << NEWLINE.
//div1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
#define CLS "\033[2J\033[1;1H"
#define NEWLINE "\n"
int main() {
while(true) {
srand(time(NULL));
int a, div1, div2;
div1=rand()%11;
div2=rand()%11;
while (div2>div1) {
swap(div1,div2);
continue;
}
if (div1%div2!=0) {
} else {
cout << CLS;
cout << NEWLINE;
do {
cout << div1 << " / " << div2 << " = ?" << endl;
cin >> a;
cout << CLS;
cout << NEWLINE;
cout << "\t\tWrong!!" << endl;
cout << NEWLINE;
} while (a!=div1/div2);
cout << CLS;
cout << NEWLINE;
cout << "\t\tCorrect!!" << endl;
cout << NEWLINE;
cout << "Hit enter to continue." << endl;
cin.ignore();
cin.get();
}
}
return 0;
}

This code can get into "divide by 0" error. This is why you would be getting error.
The line "if (div1%div2!=0) {" seems erroneous.
In this line if div2 == 0, then your code will crash.

Related

Why does my try catch exception stop working after the catch?

I have a segment of code here that runs partially. I am able to input both the characters (c, a, r) and numbers initially, but after entering a character input, the code no long accepts integer inputs. Why does this happen?
I think it has something to do with my try catch exception.
code:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int item;
string input;
float total = 0;
int flag = 0;
float maintotal = 0;
int main() {
cout.precision(2);
cout << std::fixed;
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
vendingMachine();
cout << "Enter c to checkout" << endl;
cout << "Enter a to add items" << endl;
cout << "Enter r to remove items" << endl;
while (true) {
cout << "Enter your selection: " << flush;
cin >> input;
try
{
item = stoi(input); //convert to int
}
catch (exception &e)
{
//std::cout << e.what();
flag = -1; //if not set flag
if (input == "c"){
checkout();
}
if (input == "a") {
add();
cout << "mainadd total: " << total << endl;
}
if (input == "r") {
remove();
}
}
if (flag != -1) //only execute with no errors
{
total = enterSelection();
cout << "total from main: " << total << endl;
}
}
return 0;
}
Once you've set flag to -1, it's never changed back to 0. The initialization you perform at the top of the file happens just once, before main is even called. So, after that, when you set it to -1 in the catch block, it never went to a part of the code that set it back to 0. As you saw, setting flag = 0 at the beginning of the while loop corrects that omission.

How do I restrict the user to number only inputs?

Ok, so basically I am having to make a basic program for a club at my school. I am trying to make it to where when the user inputs something that is not a number, it has an error message and loops back around to ask for the number again. This is not it exactly, but something I threw together real quick as an example.
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int a;
int b;
do{
cout << "Welcome to the equalizer. Please enter a number." << endl;
cin >> a;
cout << endl << "Ok, now I need another number." << endl;
cin >> b; //if a number is not entered, I need an error message and a loop back to the request for the number.
if(a>b){
cout << a << " is greater than " << b << endl;
}
if(b>a){
cout << b << " is greater than " << a << endl;
}
if(b=a){
cout << a << " is equal to " << b << endl;
}
cout << "restart? Enter Y if yes, or enter anything else to close." << endl;
cin >> c;
}while(c=="y" || c=="Y");
return 0;
Well, if I got it right, you can use something like "isdigit('char')". Do not forget to include "ctype.h".
In your code it will be something like:
if (!isdigit(c))
continue;
If the number may be a string like "1232321" then you may need to iterate through that string checking each char and exit if it is not...
bool error = false;
for (int i = 0; i < c.length(); i ++)
{
if (!isdigit(c[i]))
{
error = true;
break;
}
}
Hope, this helps.
P.S. Of course, "a" and "b" in your example should be of type string or char...

Why does program complain of too many commas?

Here is my code, I have attached the screenshot of what output Zybooks expects, and what my output is. I am trying to get it to output exactly what Zybooks is asking, however something seams to be wrong. It is compiling though. Or maybe Zybooks is just being stupid?
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <cstring>
using namespace std;
int main() {
string title;
string col1;
string col2;
string val;
int numCommas = 0;
vector<string> stringData;
vector<int> intData;
cout << "Enter a title for the data:" << endl;
getline(cin, title);
cout << "You entered: " << title << endl << endl;
cout << "Enter the column 1 header:" << endl;
getline(cin, col1);
cout << "You entered: " << col1 << endl << endl;
cout << "Enter the column 2 header:" << endl;
getline(cin, col2);
cout << "You entered: " << col2 << endl << endl;
while (1) {
cout << "Enter a data point (-1 to stop input):" << endl;
getline(cin, val);
if (val == "-1") {
break;
}
if (val.find(',') == -1) {
cout << "Error: No comma in string." << endl << endl;
}
else {
for (int i = 0; i < val.length(); i++) {
if (val.at(i) == ',') {
numCommas++;
if (numCommas > 1){
break;
}
}
}
if (numCommas == 1) {
stringData.push_back(val.substr(0, val.find(',')));
intData.push_back(stoi(val.substr(val.find(',') + 1, val.length() - 1)));
cout << "Data string: " << val.substr(0, val.find(',')) << endl;
cout << "Data integer: " << stoi(val.substr(val.find(',') + 1, val.length() - 1)) << endl;
}
else {
cout << "Error: Too many commas in input." << endl << endl;
}
}
}
return 0;
}
Thanks.
Thanks.
Your problem is that you initialise numCommas to zero at the start of the program rather than at the start of each author input. That means, once it exceeds one, it will stay that high at least(a), meaning future inputs will always be seen as having too many commas.
You just need to set it to zero immediately before checking each input.
(a) Well, until it wraps around (if it wraps around). But that will be an awful lot of commas you need to input :-)

compiling is okay but my program doesn't really work

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
while (1)
{
char name1[100];
char adrs1[100];
char rsn1[100];
char XXXXX[100];
cout << "input personal information" << '\n';
cout << "patient 1" << '\n';
cout << "input the name of the patient" << '\n';
cin.getline (name1,100);
cout << "input the address of the patient" << '\n';
cin.getline (adrs1,100);
cout << "input the reason" << '\n';
cin.getline (rsn1,100);
cout << "input the name of the patient" << '\n';
cout << "if you want to exit, input exit" << '\n';
cin.getline (XXXXX,100);
if (XXXXX==name1)
cout << adrs1[100] << rsn1[100] << '\n';
else (XXXXX=="exit");
break;
return 0;
}
}
that's my program, and compiling is okay. but when i start the program, it doesn't print any rsn or adrs, it just ends.
I want it to print rsn and adrs when it reads names.
Help me please
There are quite a few errors in your program.
The most important one is that you are trying to write an infinite loop. But it runs exactly once. You need to move your return statement out of the loop.
There is no need for a conditional statement for an else block. You can remove it along with the semi colon.
You're trying to print a character at the index 100 which goes out of bounds.
I don't know what XXXXX is supposed to be. May be you missed pasting the declaration on this website.
At this point, I really suggest picking up a book or trying to debug your code by going step-by-step through your code. It would be more helpful to you at this stage in your learning than this website,
To complete the answer above, the correct program would be:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
while (1)
{
char name1[100];
char adrs1[100];
char rsn1[100];
char XXXXX[100];
cout << "input personal information" << '\n';
cout << "patient 1" << '\n';
cout << "input the name of the patient" << '\n';
cin.getline (name1,100);
cout << "input the address of the patient" << '\n';
cin.getline (adrs1,100);
cout << "input the reason" << '\n';
cin.getline (rsn1,100);
cout << "input the name of the patient" << '\n';
cout << "if you want to exit, input exit" << '\n';
cin.getline (XXXXX,100);
if (strcmp(XXXXX,name1) == 0)
cout << adrs1 << rsn1 << '\n';
else /*(XXXXX=="exit");*/
break;
//return 0;
}
}
You forgot to initilize the name1 variable, you can initialize it using char name1[100] = {};
You cannot directly compare the if (XXXXX==name1), use can use the strncmp function for the same. I will prefer the string class instead of char pointer. Use the following:
if (!strncmp(XXXXX,name1,100))
cout << adrs1 << rsn1 << '\n';
else if (!strncmp(XXXXX,"exit",100))
break;

Visual Studio Appears to be ignoring my IF function

I've been trying to practice small parts of my coding for an impending assignment but for the life of me I can't get visual studio to recognise that there's an if function, it just completely skips over it. The window closes as soon as I press enter.
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter first number.";
cin >> a;
cout << "Enter second number.";
cin >> b;
if( a > b)
{
cout << "Variable a is greater than variable b." << endl;
cout << "Value of a is " << a << " value of b is " << b << endl;
}
return 0;
}
Not portable but, as you're using Visual Studio, you're on Windows, so it'll work. When you works in Debug mode, with Visual Studio, you don't need to add system("pause"), or something else, to your program. So I guess you're working in Release mode.
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter first number.";
cin >> a;
cout << "Enter second number.";
cin >> b;
if( a > b)
{
cout << "Variable a is greater than variable b." << endl;
cout << "Value of a is " << a << " value of b is " << b << endl;
}
system("pause");
return 0;
}
EDIT :
You shouldn't use std::endl for a new line, or at least not each time you need a new line. You should just write << "\n"; std::endl insert a new line character + flushes the buffer. That's important to understand the difference between << std::endl; and << "\n";