Simple program crashes for some reason - c++

I wrote simple binary calculator,which I'm going to develop.Everything works for a few first calculations,but after that the program chrashes-"Binary.exe has stopped working".I think there might be something wrong with dynamicly allocated array in function "decToBin()",but i can't spot the issue.Here's the code:
#include <iostream>
#include <math.h>
#include <string>
#include <conio.h>
using namespace std;
void binToDec()
{
string bin;
cout<<"Binary code: ";
cin>>bin;
int powr = 0;
int num = 0;
long long sum = 0;
for(int i=bin.size()-1; i>=0; i--)
{
if(bin[i] == '1')
{
num = 2;
}
else if(bin[i] == '0')
{
num = 0 ;
}
sum += pow(num,powr);
cout<<sum<<endl;
powr++;
}
cout<<"Decimal: "<<sum<<endl;
sum = 0;
powr = 0;
num = 0;
}
void decToBin()
{
int dec = 0;
cout<<"Decimal number or digit: ";
cin>>dec;
int i = 0;
int *numBin = new int[i];
while(dec > 0)
{
numBin[i] = dec%2;
dec = dec/2;
i++;
}
cout<<"Binary: ";
for(int j = i-1; j>=0; j--)
{
cout<<numBin[j];
}
cout<<"\n";
i = 0;
delete [] numBin;
}
int main()
{
//USER INPUT
int nav = 0;
while(true)
{
cout<<"\n";
cout << "1.Binary to decimal:"<<endl;
cout << "2.Decimal to binary:"<<endl;
cin>>nav;
switch(nav)
{
case 1:
{
binToDec();
break;
}
case 2:
{
decToBin();
break;
}
}
}
return 0;
}

Your problem:
int *numBin = new int[i]; //i is 0, then you add elements to it
An easy solution, use std::vector:
vector<int> numBin;
...
numBin.push_back(dec%2);
You don't have to worry about dynamic memory at all now.

Related

Program to print first 5 perfect numbers, is printing 2096128?? C++

So this program will print perfect numbers, but one of them, 2096128, is being printed for some reason? Would really appreciate some help figuring out what is happening! Thank you! I can't figure out why one non perfect number is finding it way into the sequence!
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
bool isPerfect(int n);
using namespace std;
int main() {
long long perfect = 0;
int first = 0;
first = (pow(2, 2 - 1))*(pow(2, 2) - 1);
cout << first << endl;
for (int i = 3, j = 1; j < 5; i += 2) {
if (isPerfect(i)) {
perfect = (pow(2, i - 1)*(pow(2, i) - 1));
cout << perfect << endl;
j++;
}
}
// pause and exit
getchar();
getchar();
return 0;
}
bool isPerfect(int n)
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else if (n % 2 == 0) {
return false;
}
else {
bool prime = true;
for (int i = 3; i < n; i += 2) {
if (n%i == 0) {
prime = false;
break;
}
}
return prime;
}
}
You're pretty much complicating this task.
Here's what I came up with:
#include <iostream>
using namespace std;
bool isPerfect(long long n);
int main()
{
int count = 5;
long long sum = 1;
for (int i = 3; count >= 0; i += 2)
{
sum += i * i * i;
if (isPerfect(sum))
{
cout << sum << endl;
count--;
}
}
system("pause");
return 0;
}
bool isPerfect(long long n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
sum += i;
}
return sum == n;
}
It sure isn't perfect, but will do for 5 numbers. Consider that it'll be very slow for more than 5 numbers.

.exe file stopped working when i run a c++ program(no '/0')

When i run this program (i am using codeblock and its fully upgraded), it shows a box with:
''''.exe has stopped working
A problem caused the program to stop working correctly. Windows will close the program and notify if a solution is available.''''
#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
int main()
{
int no, hlf, arr[no], arrno;
cout << "ENTER A NUMBER";
cin >> no;
hlf = ceil(no/2);
for(int i = 1;i <= no;i++)
{
for(int j = 2;j <= hlf;j++)
{
int ij = i/j;
if(j != i && ij == 0)
{
goto cont;
}
else
{
continue;
}
}
arr[arrno] = i;
arrno++;
cont: ;
}
for(int k = 0;k <= arrno;k++)
{
cout << arr[k] << " ";
}
getch();
return 0;
}
There are few mistakes in your code
no need of #include <conio.h> and getch();
Array arr[no] declaration is wrong. It should be int arr[50];
Here is the corrected code that runs fine.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int no, hlf, arrno;
int arr[50];
cout << "ENTER A NUMBER";
cin >> no;
hlf = ceil(no/2);
for(int i = 1;i <= no;i++)
{
for(int j = 2;j <= hlf;j++)
{
int ij = i/j;
if(j != i && ij == 0)
{
goto cont;
}
else
{
continue;
}
}
arr[arrno] = i;
arrno++;
cont: ;
}
for(int k = 0;k <= arrno;k++)
{
cout << arr[k] << " ";
}
return 0;
}
thanks guys, i got the answer. it was my bad, i didn't post that i need to print prime numbers. its my first question in a web forum. never used one.
ps -> thanks again
include
include
using namespace std;
int main()
{
int numb = 12, half;
int arra[50], arrno = 0;
half = ceil(numb/2);
for(int r = 2;r <= numb;r++)
{
for(int t = 2;t <= half;t++)
{
if(r%t != 0 || t == r) continue;
else goto rpp;
}
arra[arrno] = r;
arrno++;
continue;
rpp:
continue;
}
for (int v = 0;v < arrno;v++)
{
cout << arra[v] << " ";
}
return 0;
}

Adding all numbers from string

I'm trying to add all numbers from string, but I can't figure out how do I add a 2 digit number.
ex: ab32d3
I want the answer to be 35.
This is my code:
int main()
{
int max=0,min=100000,sum=0,totalsum=0;
string s;
ifstream in ("Unos.txt");
while(getline(in,s))
{
cout<<s<<endl;
for(int i=0;i<s.length();++i)
{
if(s[i]>max)
{
max=s[i]-'0';
}
if(s[i]<min)
{
min=s[i]-'0';
}
if(isdigit(s[i]))
{
sum=10*sum+s[i]-'0';
}
else
{
totalsum+=sum;
sum=0;
}
}
}
totalsum+=sum;
cout<<"Najveci broj je: "<<max<<endl;
cout<<"Najmanji broj je: "<<min<<endl;
cout<<"Zbir svih brojeva je: "<<totalsum<<endl;
return 0;
}
Try this:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string str = "ab32d3", temp;
int sum = 0;
for ( int i = 0; i < str.size(); i++ ) {
if ( isdigit(str[i]) ) temp.push_back(str[i]);
else {
if ( temp.size() > 0 ) {
sum += stoi(temp);
temp = string();
}
}
}
// Last number (if exists)
if ( temp.size() > 0 ) sum += stoi(temp);
cout << sum << endl;
return 0;
}
It will print 35
#include <iostream>
#include <cctype>
int main() {
std::string s = "ab32d3";
int value_so_far = 0;
int total = 0;
for (int i = 0; i < s.length(); ++i)
{
if (isdigit(s[i])) { // This keeps a running total until the number ends
value_so_far = 10 * value_so_far + s[i] - '0';
} else { // Here the number has ended - Add to the total and reset
total += value_so_far;
value_so_far = 0;
}
}
// Got to the end - Add what is left!
total += value_so_far;
std::cout << "Ans:" << total << std::endl;
// your code goes here
return 0;
}
Here is the link: ideone code.
Please check the comments in the code as to the explanation.

LRU c++ program

I've been working on a program in one of my college classes. I have been having trouble with the implementation of my LRU code as it is not displaying any errors or anything, but compiles. There are two parts. The main that we input the values into, which we then specify which algorithm we want to use to find page faults. I know the main works, along with the FIFO algorithm, but I'm not getting anything with my LRU code (It compiles and "runs" but displays nothing as if I did not click to use the algorithm). Can anyone help me figure out what is wrong?
main.cpp
#include <iostream>
#include <string>
//#include "fifo.cpp"
#include "lru.cpp"
//#include "optimal.cpp"
using namespace std;
int main() {
// List of different variables
string pagestring;
int fs,pn[50], n;
// Prompt for page references
cout<<"Virtual Memory Simulation\nBy blah\n----------\nEnter the number of pages : " << endl;
cin >> n;
cout<<"\n-------------\nPlease enter a list of page numbers separated by commas.\n"<< endl;
cin>>pagestring;
// algorithm to use
char algo;
while (true) {
// Prompt algorithm to use
cout<<"----------\nPlease select an algorithm to use.\n\n1: First-In-First-Out (FIFO)\n2: Least-Recently-Used (LRU)\n3: Optimal\n0: Quit\n"<<endl;
cin>>algo;
if (algo == '1') {
//fifo(pagestring);
}
else if (algo == '2'){
LRU_Execute(pagestring, n);
}
else if (algo == '3'){
cout<<"Optimal Not yet coded"<<endl;
}
else if (algo == '0'){
break;
}
else {
cout<<"Invalid choice. Please try again."<<endl;
}
}
cout<<"Goodbye!!"<<endl;
};
LRU.cpp
#include <iostream>
#include <string>
using namespace std;
class pra
{
int fs,z;
int frame[50], frame1[50][2], pn[50], n, cnt, p, x;
public:
pra();
void init(string pagestring);
void getdata(string pagestring, int n);
void lru(int* pn, int n, string pagestring);
};
pra::pra()
{
int i;
for (i = 0; i < fs; i++)
{
frame[i] = -1;
}
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
p = 0;
cnt = 0;
}
void pra::init(string pagestring)
{
int i;
for (i = 0; i < fs; i++)
{
frame[i] = -1;
}
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
p = 0;
cnt = 0;
}
void pra::getdata(string pagestring, int n)
{
fs=3;
// index to loop through input string
int i = 0;
// current input string character
char z = pagestring[i];
int x = 0;
//cout << "\nEnter the page numbers : ";
while (z != '\0'){
// skip over commas and spaces
if (!(z == ',')) {
pn[x] = z;
x++;
// cout<<pn[x]<<"-This is pn[x]\n";
}
z = pagestring[++i];
}
//cout<<pn[x]<<"-This is pn[x] AGAIN\n";
this->lru(pn, n, pagestring);
}
void pra::lru(int* pn, int n, string pagestring)
{
init(pagestring);
int ind = 0, fault = 0, pi = 0, j, fn;
char i, z;
p = 0;
cnt = 0;
int min;
cout<<n<<"---"<<i<<" - "<<j<<" - "<<" - "<<fn<<" - "<<z;
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
pi = 0;
for (i = 0; i < n; i++)
{
j = 0;
if (ind > fs - 1)
ind = 0;
fault = 1;
min = 999;
while (j < fs)
{
if (frame1[j][0] = pn[pi])
{
fault = 0;
p++;
frame1[j][1] = p;
goto l2;
}
if (frame1[j][1] < min)
{
min = frame1[j][1];
fn = j;
}
j++;
}
j = 0;
while (j < fs)
{
if (frame1[j][0] = -1)
{
fault = 1;
fn = j;
goto l2;
}
j++;
}
ind++;
l2:
if (fault == 1)
{
p++;
frame1[fn][0] = pn[pi];
frame1[fn][1] = p;
cnt++;
}
cout << "\nElement: " << pn[pi];
pi++;
for (z = 0; z < fs; z++)
{
cout << "\t" << frame1[z][0];
}
if (fault == 1)
cout << "\t**Page Fault**";
else
cout << "\t--No Page Fault--";
}
cout << "\nTotal number of page faults: " << cnt;
cout << "\n";
}
void LRU_Execute(string pagestring, int n)
{
pra p;
int j, fault = 0, i, pi, z, fn, ind = 0, ans, ch;
p.getdata(pagestring, n);
//p.lru();
while (ans == 1);
//return 1;
}

least number of digits without duplicates

I am a C++ noob. I have a list of numbers that I put into a Vector. All numbers are 9 digit integers and are unique. I want to know what is the least amount of digits (starting from the right) that can be used to uniquily identify each number in the set. right now there are only 6 numbers, but the list could potentially grow into the thousands. I have posted my code thus far (not working.)
EDIT output is the following...
digit is 1
digit is 1
digit is 1
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms
This is mostly a learning exercise. Please be generous and explicit with your comments and solutions.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main() {
//declare stream variable and load vector with values
ifstream myfile("mydata.txt");
vector<int> myVector;
int num;
while (myfile >> num) {
myVector.push_back(num);
}
//sort and squack if there is a duplicate.
std::sort(myVector.begin(), myVector.end());
for (int i = 0; i < (myVector.size() - 1); i++) {
if (myVector.at(i) == myVector.at(i + 1)) {
printf("There are duplicate student numbers in the file");
exit(EXIT_FAILURE);
}
}
//if it get here, then there are no duplicates of student numbers
vector<int> newv;
int k = 1;
bool numberFound = false;
bool myflag = false;
while (numberFound == false) {
//loop through original numbers list and add a digit to newv.
for (int j = 0; j < myVector.size(); ++j) {
newv.push_back(myVector.at(j) % (10^k));
}
sort(newv.begin(), newv.end());
for (int i = 0; i < (newv.size() - 1); i++) {
if (newv.at(i) == newv.at(i + 1)) {
//there is a duplicate for this digit. Set flag.
myflag = true;
}
if (myflag == false) {
numberFound = true;
cout << "digit is " << k << endl;
} else {
k++;
}
}
}
// for (int i = 0; i < myVector.size(); i++) {
// cout << "||" << myVector.at(i) << "||" << endl;
// }
//
// for (int i = 0; i < newv.size(); i++) {
// cout << "---" << newv.at(i) << "---" << endl;
// }
return 0;
}
Check the below code.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <math.h>
using namespace std;
int main() {
//declare stream variable and load vector with values
ifstream myfile("mydata.txt");
vector<int> myVector;
int num;
while (myfile >> num) {
myVector.push_back(num);
}
//sort and squack if there is a duplicate.
std::sort(myVector.begin(), myVector.end());
for (int i = 0; i < (myVector.size() - 1); i++) {
if (myVector.at(i) == myVector.at(i + 1)) {
printf("There are duplicate student numbers in the file");
exit(EXIT_FAILURE);
}
}
//if it get here, then there are no duplicates of student numbers
vector<int> newv;
int k = 1;
bool numberFound = false;
bool myflag = false;
int p = 1;
while (numberFound == false) {
//loop through original numbers list and add a digit to newv.
newv.clear();
p = p * 10;
for (int j = 0; j < myVector.size(); ++j) {
newv.push_back(myVector[j] % p);
}
sort(newv.begin(), newv.end());
myflag = false;
for (int i = 0; i < (newv.size() - 1); i++) {
if ( newv[i] == newv[i+1]) {
//there is a duplicate for this digit. Set flag.
myflag = true;
break;
}
}
if (myflag == true){
k ++;
}else{
numberFound = true;
cout << "digit is " << k << endl;
break;
}
}
return 0;
}
Sample Input:
123451789
123456687
125456789
123456780
Output:
digit is 4