C++ - program has stopped working - c++

The code that I posted below is supposed to work in recursion (the Sort() function) even up to 1kk times. The problem is: when the Sort() function gets into loop number 43385 the console stops working and alerts: "The program has stopped working". Is it a problem with memory? If yes, where is the bad part of the code? Greetings.
#include <iostream>
#include <string>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
if(i==n-1)
return counter;
else
Sort(i+1);
}
int main()
{
cin >> n >> a >> b;
Sort(0);
return 0;
}

Perhaps a call stack overflow because of too deep recursion?

To add to iltal's comment, you may want to print out information on strings a, b: a.size(), a.length(), a.capacity(), a.max_size()

I'm not sure what this code is trying to do. Here's a revision, with some print statements added, along with a random string generator.
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
cout << "x = " << x << " set tmp0 to " << tmp0 << " and tmp1 to " << tmp1 << endl;
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
cout << " endof sort: a is " << a << endl;
cout << " b is " << b << endl;
if(i==n-1) {
cout << "Returning counter " << counter << endl;
return counter;
} else {
cout << "Running sort(" << i << " + 1)" << endl;
Sort(i+1);
}
}
string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
int main()
{
n = 50;
srand(time(NULL));
string a0, b0;
a0 = randomStrGen(n);
a = a0;
b0 = randomStrGen(n);
b = b0;
// cin >> n >> a >> b;
cout << "Max string size is " << a.max_size() << endl;
cout << "Calling sort" << endl
<< " n is " << n << endl
<< " a is " << a << endl
<< " b is " << b << endl;
Sort(0);
cout << " endof program: a inital: " << a0 << endl;
cout << " a final: " << a << endl;
cout << " b inital: " << b0 << endl;
cout << " b final: " << b << endl;
return 0;
}

counter is of type int but it has a lot of values summed in it which may be in all larger than int. maybe try int64?

You could hard code some test cases, like n = 20, a = "xyz...", b = "abc...", and add print statements to your sort function to track what is going on. Also, it may be helpful to add some comments to clarify what the purpose of the different loops are.

Related

meet error while trying to read int number from input file

I am new to coding C++. I meet issue while trying to read 2 int number from input file, calculate them and then export to output. System showing issue at line 14,18 and 21 of the loop. Please give me advice on this. Thanks all!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("input.txt");
string word;
word.clear();
int a, b;
int count = 0;
while(file>>word)
{
count++;
if (count % 2 == 1){
a = stoi(word);
}
else {
b = stoi(word);
}
}
int TOTAL = a + b;
int Difference = a - b;
int Multiply = a * b;
int Division = a / b;
int MUD = a % b;
ofstream out("output.txt");
out << "Input Values: " << a << " " << b << endl;
out << "Sum of two numbers: " << TOTAL << endl;
out << "Difference of two numbers: " << Difference << endl;
out << "Multiply of two numbers: " << Multiply << endl;
out << "Division of two numbers: " << Division << endl;
out << "Modular division of two numbers: " << MUD << endl;
cout << "Calculation written in file" << endl;
out.close();
return 0;
}
#include <string> because you are using string functions that's the problem I think

Searching through char array

In CPP file #1, I'm trying to loop through the array to see if any of the inputed names match Mordor or the_Vale (from CPP file #2 towards the bottom), however my loop is not working and I only know how to loop through a string array, not a char
#Header File#
#ifndef KINGDOM_H
#define KINGDOM_H
namespace westeros
{
class Kingdom
{
public: //Makes this class public to the rest of the code
char m_name[32];
int m_population;
int count = 0;
};
void display(Kingdom&);
void display(Kingdom* k, int x);
void display(Kingdom* k, int x, int z);
void display(Kingdom* k, int x, char foo[]);
}
#endif
#CPP FIle #1#
#include <iostream>
#include "kingdom.h"
void display(Kingdom* k, int x, char foo[])
{
int a = 0;
int found = 0;
cout << "Searching for kingdom " << foo << " in Westeros" << endl;
for (a; a < x; a++)
{
if (k[a].m_name == foo)
//(strcmp(k[a].m_name) == 0)//Not working
{
cout << k[a].m_name << ", population " << k[a].m_population << endl;
found = 1;
}
}
if (found == 0)
{
cout << foo << " is not part of Westeros." << endl;
}
}
}
## CPP File (main) #2##
#include <iostream>
#include "kingdom.h"
using namespace std;
using namespace westeros;
int main(void)
{
int count = 0; // the number of kingdoms in the array
// TODO: declare the kingdoms pointer here (don't forget to initialize it)
Kingdom* pKingdoms = nullptr;
cout << "==========" << endl
<< "Input data" << endl
<< "==========" << endl
<< "Enter the number of kingdoms: ";
cin >> count;
cin.ignore();
pKingdoms = new Kingdom[count];
for (int i = 0; i < count; ++i)
{
// TODO: add code to accept user input for the kingdoms array
int x = 0;
x++;
cout << "Enter the name for kingdom #" << x + i << ": ";
cin >> pKingdoms[i].m_name;
cout << "Enter the number people living in " << pKingdoms[i].m_name << ": ";
cin >> pKingdoms[i].m_population;
}
cout << "==========" << endl << endl;
// testing that "display(...)" works
cout << "------------------------------" << endl
<< "The first kingdom of Westeros" << endl
<< "------------------------------" << endl;
display(pKingdoms[0]);
cout << "------------------------------" << endl << endl;
// This is where I am having the problem
display(pKingdoms, count, "Mordor");
cout << endl;
display(pKingdoms, count, "The_Vale");
cout << endl;
cout << endl;
delete[] pKingdoms;
pKingdoms = nullptr;
return 0;
}
if (k[a].m_name == foo)
This is not how you compare two C-Style strings. This only compares the pointers, which should result in false almost certainly. You could use strcmp (#include <string.h>):
if (!strcmp(k[a].m_name, foo))
A better way, though, since you're programming in C++, use std::string:
std::string m_name;
and the comparison would have worked flawlessly.

Unhandled exception at 0x012B1CA9

I am new to C++ and am trying to build a simple program that with the users input to proceed will generate a random left or right. I had the program working correctly until I added in the array to try and store each item as I have to output them as soon and the user would like to exit the loop. The program seems to compile fine but at run time I receive "Unhandled exception at 0x012B1CA9" Any help would be greatly appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = '100';
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
for (int i = 1; i < MAX; i++)
{
srand(time(NULL));
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
You have a multi-character constant here... and the behavior doesn't go as expected...
Change this line
const int MAX = '100';
to
const int MAX = 100;
Note the removed single quotes.
And secondly, I will advice you to remove the Seed of the C random generator from the for loop because, you'll likely get the same values from the rand() if you always call it immediately after seeding...
But preferable use the algorithm from C++'s random header
Here is a corrected version of your original code....
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = 100; // <---changed
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
srand(time(NULL)); //< moved to here
for (int i = 0; i < MAX; i++) // <-- modified starting index
{
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
I think that it is basically good idea to read more about C data types and declaration. Your error:
const int MAX = '100' should be const int MAX = 100 without any quotes. C++ does implicit conversion from character literals to int.

Printing multiple outputs on same line

there. I'm self learning C++ out of "C++ without fear". There is an exercise dealing with the GCD of 2 numbers that asks to print "GCD(a,b) =>" at each step in the proceedure. I was able to get this working:
int gcd (int a, int b);
int main() {
int i,j;
cout << "Enter the first integer" << endl;
cin >> i;
cout << "Enter the second integer" << endl;
cin >> j;
int k = gcd(i,j);
cout << "The GCD is " << k << endl;
system("PAUSE");
return 0;
}
int gcd (int a, int b){
if(b==0){
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " <<endl;
return a;
}
else {
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " << endl;
return gcd(b,a%b);
}
}
I was just wondering if there is a nicer way to go about printing each step of finding the GCD. That is, is there a "nicer" way to write this part of the code:
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " << endl;
? Thanks in advance.
You can do something like:
cout << "GCF(" << a << ',' << b << ") =>" << endl;
It is not C++ but you could use the C way of printing it which in my opinion looks better in this situation because there are far fewer stream operators, << in the way.
#include <cstdio>
printf("GCF(%d, %d) =>\n", a, b);
But this is a C way of doing things... You could use something like boost::format as is mentioned in this SO answer.
try this one
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
cout << 6+2 <<"\n" << 6-2;
}

"Run-Time Check Error #2 - Stack around the variable "arr" was corrupted" when I use a file with many numbers

This is supposed to read at most 1000 numbers from a file into an array and then analyze them. It works flawlessly unless I use a file with a million numbers in it. I probably because I have an infinite loop, but I can't find where. I'm not supposed to go over 1000 elements.
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
const long N=1000;
using namespace std;
//declaring the functions
int readArray(ifstream& ifile, long arr[]);
void sortArray(long arr[], int numberInTheArray);
int main()
{
//variable declaration
int n=0;
int i=0;
int numberInTheArray=0;
long minimum=0;
long maximum=0;
long arr[N]={0};
ifstream ifile;
string strVar;
cout << "Input File Name: ";
cin >> strVar;
cout << "Which number do you want to return? ";
cin >> i;
cout << endl;
ifile.open(strVar.c_str());
if(!ifile)
{
cout << "That file does not exist!" << endl;
return 1;
}
numberInTheArray = readArray(ifile,arr);
if (numberInTheArray == 0){
cout << "The file is empty!" << endl;
}
else{
maximum = arr[n];
minimum = arr[n];
n++;
while (n<=N){
if (arr[n] <= minimum){
minimum = arr[n];
}
if (arr [n] >= maximum){
maximum = arr[n];
}
n++;
}
cout << "Before Sort:\n" << " Min is {" << minimum << "}.\n" << " Max is {"
<< maximum << "}.\n";
if (i>N){
cout << " " << i << " is bigger than 1000!" << endl;
}
else if (numberInTheArray < N){
cout << " WARNING: Only " << numberInTheArray
<< " numbers were read into the array!" << endl;
if (i <= numberInTheArray){
cout << " Value " << i << " is {" << arr[i-1] << "}." << endl;
}
else {
cout << " There aren't that many numbers in the array!" << endl;
}
}
else {
cout << " Value " << i << " is {" << arr[i-1] << "}." << endl;
}
sortArray(arr,numberInTheArray);
cout << "\nAfter Sort:\n" << " Min is {" << minimum << "}.\n" << " Max is {"
<< maximum << "}.\n";
if (i>N){
cout << " " << i << " is bigger than 1000!" << endl;
}
else if (numberInTheArray < N){
cout << " WARNING: Only " << numberInTheArray
<< " numbers were read into the array!" << endl;
if (i <= numberInTheArray){
cout << " Value " << i << " is {" << arr[i-1] << "}." << endl;
}
else {
cout << " There aren't that many numbers in the array!" << endl;
}
}
else {
cout << " Value " << i << " is {" << arr[i-1] << "}." << endl;
}
}
return 0;
}
int readArray(ifstream& ifile, long arr[])
{
int n=0;
long num;
while (n<=N && ifile){
ifile >> arr[n];
n++;
}
n=n-1;
return n;
}
void sortArray(long arr[], int numberInTheArray)
{
int a;
int b;
int temp;
for (a=0; a<numberInTheArray; a++)
{
for (b=0; b<numberInTheArray; b++)
{
if (arr[a] < arr[b])
{
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
}
}
The problem is your loop conditions n <= N. Remember that array indexes goes from zero to size minus one, so the condition should be n < N.