I'm trying to sort the students by first name, grade, and id.
When I run it, it gives me the error "identifier not found."
and I'm kind of confused because I have the void sortsID in the struct before the main.
This is in my main which includes my myDate.h. I only included some of the code that I thought was important in this question
main.cpp
struct studentData {
int id;
string name;
myDate birthday;
int grade;
void sortID(studentData, int);
void sortGrade(studentData, int);
};
int main() {
studentData myClass[10];
myClass[0].name = "blah blah";
//adding names to class
//random id numbers, bday, grade for each student
for (int i = 0; i < 10; i++) {
int randomId = (rand() % (9999 - 1000 + 1)) + 1000;
int randomGrade = (rand() % (100 - 50 + 1)) + 50;
int randomMonth = rand() % (12 - 1) + 1;
int randomDay = rand() % (31 - 1) + 1;
int randomYear = rand() % (1994 - 1990) + 1990;
myDate randomBday(randomMonth, randomDay, randomYear);
myClass[i].id = randomId;
myClass[i].grade = randomGrade;
myClass[i].birthday = randomBday;
}
studentData *idSort[10];
case 2:
cout << "Sorting by ID" << endl;
sortID(myClass, 10);
cout << "Displaying original list";
cout << "Student Info:\n";
cout << "=================================================\n";
cout << "NAME ID# GRADE BDAY\n";
for (int i = 0; i < 10; i++) {
idSort[i] = &(myClass[i]);
cout << left << setw(18) << idSort[i]->name << " ";
cout << left << setw(12) << idSort[i]->id << " ";
cout << setw(11) << setprecision(4) << idSort[i]->grade << " ";
idSort[i]->birthday.display();
cout << " " << endl;
}
break;
system("PAUSE"); };
void sortID(studentData s[], int n) {
studentData temp; // Local variable used to swap records
for (int i = 0; i<n; i++)
{
for (int i = 0; i<n; i++)
{
// If s[i].student_number is greater than s[i+1].student_number,
swap the records
if (s[i].id > s[i + 1].id)
{
temp = s[i];
s[i] = s[i + 1];
s[i + 1] = temp;
}
}
}
}
void sortGrade(studentData s[], int n) {
studentData temp; // Local variable used to swap records
for (int i = 0; i<n; i++)
{
for (int i = 0; i<n; i++)
{
// If s[i].student_number is greater than s[i+1].student_number, swap the records
if (s[i].grade > s[i + 1].grade)
{
temp = s[i];
s[i] = s[i + 1];
s[i + 1] = temp;
}
}
}
}
void sort_on_name(studentData s[], int n) {
studentData temp; // Local variable used to swap records
for (int i = 0; i<n; i++)
{
for (int i = 0; i<n; i++)
{
// If s[i].name is later in alphabet than s[i+1].name, swap the two records
if (strcmp(s[i].name, s[i + 1].name) > 0)
{
temp = s[i];
s[i] = s[i + 1];
s[i + 1] = temp;
}
}
}
}
`
You declared function sortID as a non-static member function of class studentData
struct studentData {
int id;
string name;
myDate birthday;
int grade;
void sortID(studentData, int);
void sortGrade(studentData, int);
};
But you call it as a non-member function
sortID(myClass, 10);
Of course the compiler does not know how this name is declared because you declared name
studentData::sortID
Moreover the function defined after main with name sortID differs from the member function because its first parameter has type studentData s[] while the early declared function has the first parameter of type studentData
void sortID(studentData s[], int n) {
studentData temp; // Local variable used to swap records
for (int i = 0; i<n; i++)
{
for (int i = 0; i<n; i++)
{
// If s[i].student_number is greater than s[i+1].student_number,
swap the records
if (s[i].id > s[i + 1].id)
{
temp = s[i];
s[i] = s[i + 1];
s[i + 1] = temp;
}
}
}
}
Thank you guys for all your help!
I just used the #include < algorithmn >
So I just added this between the studentData and main()
struct compare_student_by_id {
bool operator() (const studentData & lhs, const studentData & rhs) {
return lhs.id < rhs.id;
}};
and included
std::sort(myClass, myClass + 10, compare_student_by_id());
in the main.
Related
I have problem with recursive functions.
I have to build a recursive function which creates an array of integer values corresponding to the digits of a given number.
For example, if I input a number like 3562, it should look like :
myArray[0] = 3
myArray[1] = 5
myArray[2] = 6
myArray[3] = 2
Here is my code :
#include <iostream>
using namespace std;
int myFunction(int num, int lenOfNum);
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
cout << myFunction(number, lengthCount) << endl;
}
int myFunction(int num, int lenOfNum){
int arr[lenOfNum];
if(num > 0){
for(int i = 0; i < lenOfNum; i++){
arr[i] = num/=10;
cout << "arr[" << i + 1 << " ]= " << arr[i] << endl;
}
return myFunction(num, lenOfNum);
}
else if(num == 0){
return 0;
} else;
}
The problem with your code is that you are calling int arr[lenOfNum] in each method call, which in short creates an array with a new reference to a memory location that can store lenOfNum integers.
To solve this, we declare the array in the main method and pass it as a parameter to the function.
int main() {
// somewhere in main after reading lenOfNum
int arr[lenOfNum];
// somewhere in main after declaring an array
myFunction(arr, number, lengthCount - 1);
}
and myFunction as
void myFunction(int *arr, int num, int idx) {
if (idx < 0) return; // you've completed processing the num
else if (num == 0) {
arr[0] = 0;
return;
}
arr[idx--] = num % 10;
myFunction(arr, num / 10, idx);
}
Using vector and rest part of your example
#include <iostream>
using namespace std;
void myFunction(vector<int> &arr, int num, int lenOfNum){
if (num < 0) {
return;
}
else if (num == 0) {
return;
}
int next_idx = lenOfNum - 1;
int digit = num % 10;
arr[next_idx] = digit;
myFunction(arr, num / 10, next_idx);
}
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
auto arr = vector<int>(lengthCount, 0);
myFunction(arr, number, lengthCount);
for(int i = 0; i < arr.size(); i++){
cout << "arr[" << i << " ]= " << arr[i] << endl;
}
}
Works for positive numbers
#include <vector>
#include <stdio.h>
std::vector<int> myFunction(int num)
{
std::vector<int> ret;
int irec = num / 10;
if (irec > 0)
ret = myFunction(irec);
ret.push_back('0' + (num % 10));
return ret;
}
int main(int argc, char *argv[])
{
std::vector<int> res = myFunction(539);
for(unsigned int i = 0; i < res.size(); i++)
printf("%c,", res[i]);
}
I'm trying to get this code to sort names but it doesn't seem to work for me. What could be wrong? I have a class named Student and want to pass the names and sort them in ascending order. So what I am trying to do is pass the 4 object firstname onto the the sort_list function and sort them in ascending order and display them afterwards. However when I run the code it shows me the same order I had and the sort function didn't seem to have done anything. See if you guys can help me out here.
#include <iostream>
#include<string>
using namespace std;
//***************************************************************************
//STUDENT CLASS
//***************************************************************************
class Student
{
private:
string firstname;
string lastname;
string studentID;
string phoneNumber;
double gpa;
public:
Student();
Student(const string&, const string&, const string&, const string&, const double&);
string getfirstName() const;
string getlastName() const;
string getstudentId() const;
string getphoneNumber() const;
double getGPA() const;
void setfirstName(string&);
void setlastName(string&);
void setstudentId(string&);
void setphoneNumber(string&);
void setGAP(double&);
};
Student::Student()
{
firstname = " ";
lastname = " ";
studentID = " ";
phoneNumber = " ";
gpa = 0;
}
Student::Student(const string&a, const string&b, const string&c, const string&d, const double&e)
{
firstname = a;
lastname = b;
studentID = c;
phoneNumber = d;
gpa = e;
}
string Student::getfirstName()const
{
return firstname;
}
string Student::getlastName()const
{
return lastname;
}
string Student::getstudentId() const
{
return studentID;
}
string Student::getphoneNumber() const
{
return phoneNumber;
}
double Student::getGPA() const
{
return gpa;
}
void Student::setfirstName(string&u)
{
firstname = u;
}
void Student::setlastName(string&v)
{
lastname = v;
}
void Student::setstudentId(string&x)
{
studentID = x;
}
void Student::setphoneNumber(string&y)
{
phoneNumber = y;
}
void Student::setGAP(double&z)
{
gpa = z;
}
//***************************************************************************
//COURSE CLASS
//***************************************************************************
class Course :public Student
{
private:
string code;
int section;
int capacity;
int numStudents;
Student *list;
public:
Course();
Course(string, int, int);
~Course();
string getCourseCode();
int getSection();
int getCapacity();
int getNumStudents();
void setCourseCode(string);
void setSection(int);
void add(const Student&);
void display();
void display(const string, const int);
void remove(const string m, const int n);
void sort_list();
};
Course::Course()
{
code = "CMPT1020";
section = 1;
capacity = 35;
numStudents = 0;
list = new Student[35];
}
Course::Course(string a, int b, int c)
{
code = a;
section = b;
capacity = c;
numStudents = 0;
list = new Student[c];
}
Course::~Course()
{
delete[] list;
list = nullptr;
}
string Course::getCourseCode()
{
return code;
}
int Course::getSection()
{
return section;
}
int Course::getCapacity()
{
return capacity;
}
int Course::getNumStudents()
{
return numStudents;
}
void Course::setCourseCode(string a)
{
code = a;
}
void Course::setSection(int b)
{
section = b;
}
void Course::add(const Student& s)
{
if (numStudents == capacity)
{
cout << "Course is full" << endl;
return;
}
list[numStudents] = s;
numStudents++;
int i = numStudents - 2;
while (i >= 0 && (s.getGPA() > list[i].getGPA()))
{
list[i + 1] = list[i];
i--;
}
list[i + 1] = s;
}
void Course::display()
{
for (int i = 0; i < numStudents; i++)
{
cout<<list[i].getfirstName() <<" "<< list[i].getlastName() <<" "<< list[i].getstudentId() <<" "<< list[i].getphoneNumber() <<" "<< list[i].getGPA() << endl;
}
}
void Course::display(const string x, const int y)
{
if (y == 1)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getfirstName() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 2)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getlastName() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 3)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getstudentId() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 4)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getphoneNumber() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
}
void Course::remove(const string a, const int b)
{
if (b == 1)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getfirstName() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 2)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getlastName() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 3)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getstudentId() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 4)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getphoneNumber() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
}
void Course::sort_list()
{
string temp;
for (int i = 0; i < numStudents; i++)
{
for (int j = 0; j < numStudents-1; j++)
{
if(list[j].getfirstName() >list[j+1].getfirstName())
{
temp = list[j].getfirstName();
list[j].getfirstName() = list[j+1].getfirstName();
list[j+1].getfirstName() = temp;
}
}
}
}
int main()
{
Student a("Kevin", "Chen", "300215915", "7788408028", 2);
Student b("Mickey", "Mouse", "12345678", "2222222222", 2.5);
Student c("Donald", "Duck", "24681012", "3333333333", 3.0);
Student d("Goofy", "Dog", "3579111315", "5555555555", 3.5);
Course x;
x.add(a);
x.add(b);
x.add(c);
x.add(d);
x.display();
cout << endl;
x.sort_list();
x.display();
/*cout << " " << endl;
x.remove("kevin", 1);
x.remove("Chen", 2);
x.remove("300215915", 3);
x.remove("7788408028", 4);
x.display();
cout << endl;
x.display("kevin", 1);
x.display("Mouse", 2);
x.display("24681012", 3);
x.display("5555555555", 4);*/
system("pause");
return 0;
}
It is true that your sorting code doesn't do anything.
Here is the core of it:
temp = list[j].getfirstName();
list[j].getfirstName() = list[j+1].getfirstName();
list[j+1].getfirstName() = temp;
getfirstName() returns the first name by value so all your assignments are doing is swapping temporary copies of the first names. There is no effect on the actual list elements.
I think you meant:
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
This also means temp must be declared as a Student, not a std::string.
Also, unless I'm misremembering how Bubble Sort works (which is certainly possible — given its uselessness in the real world, it's been a long time since I've written one), your outer loop needs as many iterations as it takes for the inner loop not to be doing any swaps any more. If that's somehow inherently capped at numStudents iterations, I can't see why, nor see any evidence of it on the Wikipedia article.
Assuming I am on the right lines with that, I'd have the function looking like this:
void Course::sort_list()
{
bool go_again = false;
do {
go_again = false;
for (int i = 0; i < numStudents-1; i++) {
if (list[i].getfirstName() > list[i+1].getfirstName()) {
Student temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
go_again = true;
}
}
} while(go_again);
}
(live demo)
I'm new to C++ programming.
Now I have the state class. I want to create neighboring states with this class, so I add the function getNeighboringStates() to my class. In this function I pass in "neighboring_states" to function set_neighboring_state(), this function change "neighboring_states"'s value.
In this function, I set a for loop to test. It print out "7 1 0 3 6 4 5 2 8", which is the value I want. But In the function getNeighboringStates(), I also set a for loop that has the same mission as in set_neighboring_state(), but the screen display "0 1 4716672 2686652 2686528 0 4716676 4519501 4716676".
I don't know what's wrong with my code. What do I need to do now?
int n; // The number of columns as well as rows of the board
int k; // The kind of heuristic function to use
int tilesCount; // The number of tiles, including the blank one
int statesCount; // The number of states generated
int* m_initTiles;
int* m_goalTiles;
int tmpTile;
const int UP = 0;
const int DOWN = 1;
const int RIGHT = 2;
const int LEFT = 3;
int* direction;
class State {
public:
State(){}
int getBlankTilePosition() {
for (int i = 0; i < n * n; i++) {
if (stateTiles[i] == 0)
return i;
}
}
void set_neighboring_state(State* neighboring_state, int direction) {
int blankPosition = getBlankTilePosition();
int neighbor_tiles[n * n];
for (int i = 0; i < n * n; i++) {
neighbor_tiles[i] = getStateTiles()[i];
}
switch(direction) {
case UP:
if (blankPosition/n < 1) return;
else {
swap(neighbor_tiles[blankPosition], neighbor_tiles[blankPosition - n]);
neighboring_state->set_tiles(neighbor_tiles);
// This for loop print out "7 1 0 3 6 4 5 2 8"
for (int i = 0; i < n * n; i++)
cout << neighboring_state.getStateTiles()[i] << " "; cout << endl;
}
break;
case DOWN:
if (blankPosition/n == n - 1) return;
else {
swap(neighbor_tiles[blankPosition], neighbor_tiles[blankPosition + n]);
neighboring_state->set_tiles(neighbor_tiles);
}
break;
case LEFT:
if (blankPosition % n == 0) return;
else {
swap(neighbor_tiles[blankPosition], neighbor_tiles[blankPosition - 1]);
neighboring_state->set_tiles(neighbor_tiles);
}
break;
default:
if ((blankPosition + 1) % n == 0) return;
else {
swap(neighbor_tiles[blankPosition], neighbor_tiles[blankPosition + 1]);
neighboring_state->set_tiles(neighbor_tiles);
}
break;
}
}
/*
The maximum number of neighboring state that can be created is 4.
This function return the neighboring states of a certain state.
The first state represents for the "left" neighbor, the second,
the third and the fourth represent the "right", "up, and "down"
neighbor, respectively.
*/
State* getNeighboringStates() {
State* neighboring_states;
neighboring_states = new State[4];
for (int i = 0; i < 4; i++)
set_neighboring_state(&neighboring_states[i], direction[i]);
// This print out "0 1 4716672 2686652 2686528 0 4716676 4519501 4716676"
cout << endl;
for (int i = 0; i < n * n; i++)
cout << neighboring_states[0].getStateTiles()[i] << " ";
cout << endl;
return neighboring_states;
}
State(int* pStateTiles) {
stateTiles = pStateTiles;
}
void set_tiles(int* tiles) {
stateTiles = tiles;
}
int* getStateTiles() {
return stateTiles;
}
private:
int* stateTiles;
};
void input(const char* fileName) {
ifstream fin;
fin.open(fileName);
// read n, k from file
fin >> n >> k;
// allocate m_initTiles and m_goalTiles memory
m_initTiles = new int[n * n];
m_goalTiles = new int[n * n];
for (int i = 0; i < n * n; i++)
fin >> m_initTiles[i];
for (int i = 0; i < n * n; i++)
fin >> m_goalTiles[i];
for (int i = 0; i < n * n; i++)
cout << m_initTiles[i] << " ";
cout << endl;
for (int i = 0; i < n * n; i++)
cout << m_goalTiles[i] << " ";
cout << endl;
fin.close();
}
void initDirection() {
direction = new int[4];
direction[0] = UP;
direction[1] = DOWN;
direction[2] = RIGHT;
direction[3] = LEFT;
}
int main() {
input("nPuzzle.inp");
initDirection();
State init_state (m_initTiles);
State goal_state (m_goalTiles);
State* init_neighbor = init_state.getNeighboringStates();
// int* state_tile = init_neighbor[0].getStateTiles();
// for (int i = 0; i < n * n; i++)
// cout << state_tile[i] << " ";
return 0;
}
int blankPosition = getBlankTilePosition();
int neighbor_tiles[n * n];
Remove int neighbor_tiles[n * n]; line from above code segment and make it global available to all function , so declare it as data of a class not for function i.e. add int neighbor_tiles[n * n]; to class as an data type .
I need to create a generic function that changes from any starting base, to any final base. I have everything down, except my original function took (and takes) an int value for the number that it converts to another base. I decided to just overload the function. I am Ok with changing between every base, but am slightly off when using my new function to take in a string hex value.
The code below should output 1235 for both functions. It does for the first one, but for the second, I am currently getting 1347. Decimal to Hex works fine - It's just the overloaded function (Hex to anything else) that is slightly off.
Thanks.
#include <iostream>
#include <stack>
#include <string>
#include <cmath>
using namespace std;
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, int num);
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, string s);
int main()
{
stack<int> myStack;
string hexNum = "4D3";
switchBasesFunction(myStack, 8, 10, 2323);
cout << endl << endl;
switchBasesFunction(myStack, 16, 10, hexNum);
return 0;
}
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, int num)
{
int totalVal = 0;
string s = to_string(num);
for (int i = 0; i < s.length(); i++)
{
myStack.push(s.at(i) - '0');
}
int k = 0;
while (myStack.size() > 0)
{
totalVal += (myStack.top() * pow(startBase, k++));
myStack.pop();
}
string s1;
while (totalVal > 0)
{
int temp = totalVal % finalBase;
totalVal = totalVal / finalBase;
char c;
if (temp < 10)
{
c = temp + '0';
s1 += c;
}
else
{
c = temp - 10 + 'A';
s1 += c;
}
}
for (int i = s1.length() - 1; i >= 0; i--)
{
cout << s1[i];
}
cout << endl << endl;
}
void switchBasesFunction(stack<int> & myStack, int startBase, int finalBase, string s)
{
int totalVal = 0;
for (int i = 0; i < s.length(); i++)
{
myStack.push(s.at(i) - '0');
}
int k = 0;
while (myStack.size() > 0)
{
totalVal += (myStack.top() * pow(startBase, k++));
myStack.pop();
}
string s1;
while (totalVal > 0)
{
int temp = totalVal % finalBase;
totalVal = totalVal / finalBase;
char c;
if (temp < 10)
{
c = temp + '0';
s1 += c;
}
else
{
c = temp - 10 + 'A';
s1 += c;
}
}
for (int i = s1.length() - 1; i >= 0; i--)
{
cout << s1[i];
}
cout << endl << endl;
}
Sorry, but I'm having issues understanding your code, so I thought I'd simplify it.
Here's the algorithm / code (untested):
void convert_to_base(const std::string& original_value,
unsigned int original_base,
std::string& final_value_str,
unsigned int final_base)
{
static const std::string digit_str =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if ((original_base > digit_str.length()) || (final_base > digit_str.length())
{
std::cerr << "Base value exceeds limit of " << digit_str.length() << ".\n";
return;
}
// Parse string from right to left, smallest value to largest.
// Convert to decimal.
unsigned int original_number = 0;
unsigned int digit_value = 0;
int index = 0;
for (index = original_value.length(); index > 0; --index)
{
std::string::size_type posn = digit_str.find(original_value[index];
if (posn == std::string::npos)
{
cerr << "unsupported digit encountered: " << original_value[index] << ".\n";
return;
}
digit_value = posn;
original_number = original_number * original_base + digit_value;
}
// Convert to a string of digits in the final base.
while (original_number != 0)
{
digit_value = original_number % final_base;
final_value_str.insert(0, 1, digit_str[digit_value]);
original_number = original_number / final_base;
}
}
*Warning: code not tested via compiler.**
The program builds and runs, however after entering the first integer and pressing enter then the error pop up box appears, then after pressing ignore and entering the second integer and pressing enter the pop up box appears and after pressing ignore it returns the correct answer. I am at my wits end with this can somebody help me fix the pop up box thing.
#include "stdafx.h"
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
#define numbers 100
class largeintegers {
public:
largeintegers();
void
Input();
void
Output();
largeintegers
operator+(largeintegers);
largeintegers
operator-(largeintegers);
largeintegers
operator*(largeintegers);
int
operator==(largeintegers);
private:
int integer[numbers];
int len;
};
void largeintegers::Output() {
int i;
for (i = len - 1; i >= 0; i--)
cout << integer[i];
}
void largeintegers::Input() {
string in;
int i, j, k;
cout << "Enter any number:";
cin >> in;
for (i = 0; in[i] != '\0'; i++)
;
len = i;
k = 0;
for (j = i - 1; j >= 0; j--)
integer[j] = in[k++] - 48;
}
largeintegers::largeintegers() {
for (int i = 0; i < numbers; i++)
integer[i] = 0;
len = numbers - 1;
}
int largeintegers::operator==(largeintegers op2) {
int i;
if (len < op2.len) return -1;
if (op2.len < len) return 1;
for (i = len - 1; i >= 0; i--)
if (integer[i] < op2.integer[i])
return -1;
else if (op2.integer[i] < integer[i]) return 1;
return 0;
}
largeintegers largeintegers::operator+(largeintegers op2) {
largeintegers temp;
int carry = 0;
int c, i;
if (len > op2.len)
c = len;
else
c = op2.len;
for (i = 0; i < c; i++) {
temp.integer[i] = integer[i] + op2.integer[i] + carry;
if (temp.integer[i] > 9) {
temp.integer[i] %= 10;
carry = 1;
} else
carry = 0;
}
if (carry == 1) {
temp.len = c + 1;
if (temp.len >= numbers)
cout << "***OVERFLOW*****\n";
else
temp.integer[i] = carry;
} else
temp.len = c;
return temp;
}
largeintegers largeintegers::operator-(largeintegers op2) {
largeintegers temp;
int c;
if (len > op2.len)
c = len;
else
c = op2.len;
int borrow = 0;
for (int i = c; i >= 0; i--)
if (borrow == 0) {
if (integer[i] >= op2.integer[i])
temp.integer[i] = integer[i] - op2.integer[i];
else {
borrow = 1;
temp.integer[i] = integer[i] + 10 - op2.integer[i];
}
} else {
borrow = 0;
if (integer[i] - 1 >= op2.integer[i])
temp.integer[i] = integer[i] - 1 - op2.integer[i];
else {
borrow = 1;
temp.integer[i] = integer[i] - 1 + 10 - op2.integer[i];
}
}
temp.len = c;
return temp;
}
largeintegers largeintegers::operator*(largeintegers op2) {
largeintegers temp;
int i, j, k, tmp, m = 0;
for (i = 0; i < op2.len; i++) {
k = i;
for (j = 0; j < len; j++) {
tmp = integer[j] * op2.integer[i];
temp.integer[k] = temp.integer[k] + tmp;
temp.integer[k + 1] = temp.integer[k + 1] + temp.integer[k] / 10;
temp.integer[k] %= 10;
k++;
if (k > m) m = k;
}
}
temp.len = m;
if (temp.len > numbers) cout << "***OVERFLOW*****\n";
return temp;
}
using namespace std;
int main() {
int c;
largeintegers num1, num2, result;
num1.Input();
num2.Input();
num1.Output();
cout << " + ";
num2.Output();
result = num1 + num2;
cout << " = ";
result.Output();
cout << "\n\n";
num1.Output();
cout << " - ";
num2.Output();
result = num1 - num2;
cout << " = ";
result.Output();
cout << "\n\n";
num1.Output();
cout << " * ";
num2.Output();
result = num1 * num2;
cout << " = ";
result.Output();
cout << "\n\n";
c = num1 == num2;
num1.Output();
switch (c) {
case -1:
cout << " is less than ";
break;
case 0:
cout << " is equal to ";
break;
case 1:
cout << " is greater than ";
break;
}
num2.Output();
cout << "\n\n";
system("pause");
}
It seems you are falling victim to the difference between C-style strings and C++ strings. C-style strings are a series of chars followed by a zero (or null) byte. C++ strings are objects that contain a series of characters (usually char, but eventually this will be an assumption you should break) and that know their own length. C++ strings can contain null bytes in the middle of themselves without problem.
To loop through all of the characters of a C++-style string, you can do one of a number of things:
You can use the .size() or .length() members of a string variable to find the number of characters in it, as in for (int i=0; i<str.size(); i++) { char c = str[i];
You can use .begin() and .end() to get iterators to the beginning and end of the string, respectively. A for loop in the form for (std::string::iterator it=str.begin(); it!=str.end(); ++it) will loop you through the members of the string by accessing *it.
If you're using C++11, you can use the for loop construct as follows: for (auto c: str) where c will be of the type of a character of the string str.
In the future, to solve problems like these, you can try using the debugger to see what happens when your program crashes or hits an exception. You likely would find that inside of largeintegers::Input() you running into either a memory access violation or some other problem.
Finally, as a future-looking criticism, you should not use C-style arrays (where you say int integer[ numbers ];) in favor of using C++-style containers, such as vector. A vector is a series of objects (such as ints) that can expand as needed.