Unhandled exception at 0x012B1CA9 - c++

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.

Related

In C++ how to put a variable inside an array?

#include <iostream>
#include <cmath>
using namespace std;
bool narcissistic(int value)
{
cout << "value is:" << value << endl;
int digitNumber = (log10(value) + 1);
cout << "Digit Number:" << digitNumber << endl;
int sum = 0;
int arr[5];
for (int i = 0; i <= digitNumber - 1; i++)
{
cout << "i digit:" << i << endl;
int exponential = pow(10, i);
arr[i] = (value % (exponential *10)) / pow(10, i);
cout << arr[i] << endl;
sum += pow(arr[i], digitNumber);
cout << pow(arr[i], digitNumber) << endl;
cout << i << "'th sum value:" << sum << endl;
}
return true;
}
int main() {
int value = 153;
narcissistic(value);
return 0;
}
In this code here;
I had to write:
int arr[5];
But I wanted the size of this array to be a variable so that its size could be defined and its values could be put by for loop so its size could be equal to the amount of loop.
I wanted to write like this:
for (int i = 0; i <= digitNumber - 1; i++)
{
int arr[i];
cout << "i digit:" << i << endl;
int exponential = pow(10, i);
arr[i] = (value % (exponential *10)) / pow(10, i);
cout << arr[i] << endl;
sum += pow(arr[i], digitNumber);
cout << pow(arr[i], digitNumber) << endl;
cout << i << "'th sum value:" << sum << endl;
}
Visual Studio says that the value that the array takes as length must be constant that's why you can't determine it by loops etc.
Is there a way to put a variable as size in an array and assign an array's size by a loop in C++?
You probably want something like this:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
bool narcissistic(int value)
{
cout << "value is:" << value << endl;
int digitNumber = (log10(value) + 1);
cout << "Digit Number:" << digitNumber << endl;
int sum = 0;
std::vector<int> arr(digitNumber); // initialize a vector containing
// digitNumber elements
for (int i = 0; i <= digitNumber - 1; i++)
{
cout << "i digit:" << i << endl;
int exponential = pow(10, i);
arr[i] = value % (exponential * 10) / pow(10, i);
cout << arr[i] << endl;
sum += pow(arr[i], digitNumber);
cout << pow(arr[i], digitNumber) << endl;
cout << i << "'th sum value:" << sum << endl;
}
// printf values in arr
cout << "arr: ";
for (auto& value : arr)
cout << value << ", ";
return true;
}
int main() {
int value = 153;
narcissistic(value);
return 0;
}
But this is a rather convoluted way to decompose a number into it's digits. You don't need floating point arithmetic at all to do this:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
bool narcissistic(int value)
{
cout << "value is:" << value << endl;
std::vector<int> arr; // start off with an empty vector
for (int i = 0; value != 0; i++)
{
arr.push_back(value % 10); // add to the vector
value /= 10;
}
// printf values in arr
cout << "arr: ";
for (auto& value : arr)
cout << value << ", ";
return true;
}
int main() {
int value = 153;
narcissistic(value);
return 0;
}
If you want to avoid using vector, you can use this:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
bool narcissistic(int value)
{
cout << "value is:" << value << endl;
int digitNumber = (log10(value) + 1);
cout << "Digit Number:" << digitNumber << endl;
int sum = 0;
vector<int> v(digitNumber);
int *arr = &v[0];
for (int i = 0; i <= digitNumber - 1; i++)
{
cout << "i digit:" << i << endl;
int exponential = pow(10, i);
arr[i] = value % (exponential * 10) / pow(10, i);
cout << arr[i] << endl;
sum += pow(arr[i], digitNumber);
cout << pow(arr[i], digitNumber) << endl;
cout << i << "'th sum value:" << sum << endl;
}
// print values in arr
cout << "arr: ";
for (int i = 0; i <= digitNumber - 1; i++)
cout << arr[i] << ", ";
return true;
}
int main() {
int value = 153;
narcissistic(value);
return 0;
}

Palindroms numbers between 1 to 10000

I want to write a program which displays palindromes numbers between 1 and 10000, I wrote a script which displays if the number typed by the user is a palindrome or no but when I add the for loop it gives me false results
My code:
#include<iostream>
using namespace std;
int main()
{
int num, reverse = 0, remainder, temp;
for(num=0;num<1000;num++){
temp = num;
cout << "temp = " << temp << endl;
while( temp != 0)
{
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp = temp / 10;
cout << "remainder = " << remainder << endl;
cout << "reverse = " << reverse << endl;
cout << "temp = " << temp << endl;
}
cout << "Reversed number: " << reverse << endl;
if (num == reverse)
cout << "\n" << num << " is a palindrome number." << endl;
else
cout << "\n" << num << " is not a palindrome number." << endl;
}
return 0;
}
You need to make sure that reverse is always 0 at the start of loop iteration:
for(num=0;num<1000;num++){
reverse = 0;
temp = num;
cout << "temp = " << temp << endl;
while( temp != 0)
{
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp = temp / 10;
cout << "remainder = " << remainder << endl;
cout << "reverse = " << reverse << endl;
cout << "temp = " << temp << endl;
}
cout << "Reversed number: " << reverse << endl;
if (num == reverse)
cout << "\n" << num << " is a palindrome number." << endl;
else
cout << "\n" << num << " is not a palindrome number." << endl;
}
Managing variables becomes much easier if you declare them where you need them instead of lumping everything together:
int main()
{
for(int num=0;num<1000;num++){
int reverse = 0;
int temp = num;
int remainder = 0;
cout << "temp = " << temp << endl;
while( temp != 0)
{
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp = temp / 10;
cout << "remainder = " << remainder << endl;
cout << "reverse = " << reverse << endl;
cout << "temp = " << temp << endl;
}
cout << "Reversed number: " << reverse << endl;
if (num == reverse)
cout << "\n" << num << " is a palindrome number." << endl;
else
cout << "\n" << num << " is not a palindrome number." << endl;
}
return 0;
}
Now you are sure remainder is always initialized at the start of for loop iteration and it cannot live longer than one iteration (for example, it won't live to the next iteration).
I checked your program and noticed a few flaws:
1) All 1-digit numbers are Palindrome because their is reverse is same.
---Your program didn't display them as palindromes.
2) You don't have to display all the details like their remainder and reverse.
---Obviously the Palindromes reverse will be the same as the original. We don't need to display non-palindromes. In some cases reverse was displaying garbage values as well. I don't find a reason that will be of any help to the user.
Solution:-
#include<iostream>
using namespace std;
bool findPalindrome(const int);
int main()
{
for (int i = 0; i < 10000; i++) {
if (findPalindrome(i)) {
cout << "Number " << i << " is a Palindrome!" << endl;
}
}
return EXIT_SUCCESS; // Return EXIT_SUCCESS is my Specialty :D
}
bool findPalindrome(const int num) {
int temp = num;
int reve = 0;
while (temp != 0) {
reve = (reve * 10) + (temp % 10);
temp /= 10;
}
return (reve == num);
}
In addition to the excellent codes other people have posted (I would go with those), this is another (and more readable) way in which you can do the same thing..
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
bool isPalindrome(unsigned number) {
std::vector<unsigned> number_as_vec;
while (number) {
number_as_vec.push_back(number % 10);
number /= 10;
}
for (size_t i = 0, j = number_as_vec.size() - 1; i < j; i++, j--) {
if (number_as_vec.at(i) != number_as_vec.at(j)) {
return false;
}
}
return true;
}
int main(int argc) {
unsigned num = 1;
while (num != 10001) {
if (isPalindrome(num)) {
std::cout << num << "\n";
}
num++;
}
return 0;
}
Also, instead of using vectors, one can simply use a string here:
bool isPalindrome(unsigned number) {
std::string num_as_string(std::to_string(number));
for (size_t i = 0, j = number_as_string.size() - 1; i < j; i++, j--) {
if (number_as_string.at(i) != number_as_string.at(j)) {
return false;
}
}
return true;
}

How to prevent frequency table to count ''empty boxes'' in c++

I wrote the below code (for homework) that is counting letters and numbers and generates a frequency table.
My question is: how to stop the frequency generation when the letter or number does not exist?
With the code I wrote, the program is counting every letter that are being fed to it but is also publishing a line for every possible letter/number in the ASCII code.
I hope I asked my question right and I appreciate any help or advice!
#include <iostream>
#include <string>
using namespace std;
int countingLetters(string someWords);
int countingNumbers(string someWords);
int frequency(string someWords, double totalChar);
int main() {
string someWords;
cout << "Write a some words: " << endl;
getline(cin, someWords);
cout << "You wrote:" << someWords << '\n';
cout << "Your sentence has " << someWords.length() << " characters." << '\n';
double totalChar = someWords.length();
cout << "Your sentence has " << countingLetters(someWords) << " letters." << '\n';
cout << "Your sentence has " << countingNumbers(someWords) << " numbers." << '\n';
cout << "Frequency of signs and letters :" << endl;
frequency(someWords, totalChar);
return 0;
}
int countingLetters(string someWords) {
int count = 0;
for (int i = 0; i < someWords.length(); i++) {
if (someWords[i] >= 'a' && someWords[i] <= 'z')
count++;
}
return count;
}
int countingNumbers(string someWords) {
int count = 0;
for (int i = 0; i < someWords.length(); i++) {
if (isdigit(someWords[i]) != 0)
count++;
}
return count;
}
int frequency(string someWords, double totalChar) {
cout << " Letter" << '\t' << "Antal" << '\t' << "Procent" << endl;
int frequency[255]={0};
for (int i = 0; i < someWords.length(); i++) {
char c = someWords[i];
if (isdigit(c) != 0)
frequency[c]++;
if (isalpha(c) != 0)
frequency[c]++;
}
for (int i = 0; i < sizeof(frequency); i++) {
if(frequency[i]>0)
cout << '\t' << static_cast<char>(i) << '\t' << frequency[i] << '\t' << frequency[i]/totalChar << endl;
}
return 0;
}
sizeof(frequency) is the size of the frequency array in bytes. You want the number of elements which is the size in bytes if the array divided by the size in bytes of one array element:
This is the number of elements of the frequency array:
sizeof(frequency) / sizeof(frequency[0])
But as you are using C++ you shouln't use raw arrays but std::array:
#include <array>
...
int frequency(string someWords, int totalChar) {
cout << " Letter" << '\t' << "Antal" << '\t' << "Procent" << endl;
std::array<int, 255> frequency{0};
for (int i = 0; i < someWords.length(); i++) {
char c = someWords[i];
if (isdigit(c) != 0)
frequency[c]++;
if (isalpha(c) != 0)
frequency[c]++;
}
int x = frequency.max_size();
for (int i = 0; i < frequency.max_size(); i++) {
if (frequency[i]>0)
cout << '\t' << static_cast<char>(i) << '\t' << frequency[i] << '\t' << frequency[i] / totalChar << endl;
}
return 0;
}
There is still room for improvement.

Access Violation Violation Location With Low Numbers

I'm working on an assignment for school. The code is supposed to read form a file and create an array, then sort the values of the array to output certain info. It works just fine as long as I have 3+ lines of info in the file. If not, I get the following error:
First-chance exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
Unhandled exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
I can't figure out why, any help would be appreciated. Here's the code:
#include <iostream> //calls the information needed
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std; //sets all unmarked commands to std::
const int ARRSIZE = 1000;
struct Student
{
string firstName;
string lastName;
string id, temp;
double gpa;
};
int readArray(ifstream& ifile, Student arr[]);
void swapElements(Student arr[], int i, int j);
void sortArray(Student arr[], int numberInTheArray);
int main()
{ // Declares the needed variables
double sought, min, max;
int i, ival, returnvar, count = 0, mincount, maxcount;
string filename;
ifstream ifile;
Student arr[ARRSIZE];
cout << "Input File Name: ";//requesting the file name
cin >> filename;
ifile.open(filename.c_str());//opening the file
if (!ifile)//checking if it opened or not
{
cout << endl << "That file does not exist!" << endl;//informing the user it did
return 1;//not open and returning 1
}
cout << "Which number do you want to return? ";//requesting the desired number
cin >> ival;
i = ival - 1;
cout << endl;
returnvar = readArray(ifile, arr);
min = arr[0].gpa;
max = arr[0].gpa;
sought = arr[0].gpa;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
if (count == 0)
{
cout << "The file is empty!" << endl;
return 1;
}
cout << "Before Sort:" << endl;
cout << " Min GPA is " << min << " for " << arr[mincount].lastName << "." << endl;
cout << " Max GPA is " << max << " for " << arr[maxcount].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
sortArray(arr, returnvar);
count = 0;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
cout << "After Sort:" << endl;
cout << " Array[0] GPA is " << min << " for " << arr[0].lastName << "." << endl;
cout << " Array[" << (returnvar - 1) << "] GPA is " << max << " for " << arr[(returnvar - 1)].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
return 0;
}
int readArray(ifstream& ifile, Student arr[])
{
int counter = 0;
while ((ifile) && (counter <= ARRSIZE))
{
ifile >> arr[counter].firstName;
ifile >> arr[counter].lastName;
ifile >> arr[counter].id;
ifile >> arr[counter].gpa;
counter++;
}
return (counter - 1);
}
void sortArray(Student arr[], int numberInTheArray)
{
for (int i = 0 ; i < numberInTheArray - 1; i++)
{
for (int j = 0 ; j < numberInTheArray - 1; j++)
{
if ( arr[j].gpa > arr[j + 1].gpa)
{
swapElements(arr, j, j+1);
}
}
}
}
void swapElements(Student arr[], int i, int j)
{
Student temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Please ignore the insanity and comments. Like I said, for an entry level course.
Try replacing counter <= ARRSIZE with counter < ARRSIZE (a rule of thumb in C is: never use <= in operations related to container sizes).
EDIT: also in your main(), you must check that i < ARRSIZE (equivalently, return error if i >= ARRSIZE). At present you seem to accept the case i == ARRSIZE, which is also wrong. And finally, readArray should return counter (that is, one more than the last written index).

my baseball program should run but I just can't find the problem why it won't. look program over

This program uses arrays to hold baseball scores for 9 innings. It calculates the high scoring team for each inning and the overall winner of the game.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
const int n = 9;
void PrintInput(char[], int[], char[], int[]);
void InningWinner(char[], int[], char[], int[]);
int main()
{
int scores1[n];
int scores2[n];
char team1[n], team2[n];
PrintInput(team1,scores1,team2,scores2);
InningWinner(team1,scores1,team2,scores2);
return 0;
}
void PrintInput(char t1[], int s1[], char t2[], int s2[])
{
cout << "\n********************************************************************\n";
cout << "Team 1: " << t1 << " ";
for (int i = 0; i < n; i++){
cout << setw(5) << s1[i];
}
cout << "\n";
cout << "Team 2: " << t2 << " ";
for (int i = 0; i < n; i++){
cout << setw(5) << s2[i];
}
}
void InningWinner(char t1[], int s1[], char t2[], int s2[])
{
for (int i = 0; i < n; i++){
if (s1[i] > s2[i])
cout << endl << t1 << " Wins Inning " << i + 1 << endl;
else if (s2[i] > s1[i])
cout << endl << t2 << " Wins Inning " << i + 1 << endl;
else if (s1[i] == s2[i])
cout << endl << " Inning " << i+1 << " ends in a TIE" << endl;
}
}
All your arrays are used without explicit initialization, which will produced undefined results.
You need to read values into scores1/2 and teams1/2 before you print them or do calculations. You could read from std::cin as in:
std::cout << "Enter " << n << " scores then press enter: ";
int num_scores_read;
for (num_scores_read = 0; std::cin >> scores1[num_scores_read]; ++num_scores_read)
;
if (!std::cin || num_scores_read < n)
{
std::cerr << "error reading score number " << num_scores_read << '\n';
exit(EXIT_FAILURE);
}
(similar for scores2 etc.)
OR, you could read them from a file (similar to above, but use
#include <fstream>
std::ifstream file(filename);
...as above but use "file" in place of "std::cin"...
OR, just hard code some sample values in your program to get you started:
int scores1[n] = { 1, 3, 5, 1, 3, 5, 4, 5, 3 };