Parenthesized Expression (Infix and Post fix) Conversion and Evaluation - c++

I have the below code working fine but outputs only 2nd input, not 1st or 3rd.
My code should get fully parenthesized expression from console and convert it to postfix expression and then that postfix expression should be evaluated in modulo 10.Therefore, all results (including intermediate results) are single decimal digits in {0, 1, …, 9}. I need to store only single digits in the stack.
My inputs and outputs are shown in below.I only got 2nd input correctly.
Please advise.
Expression 1: (((2+(5^2))+7)
Answer:
252^+7+
4 in modulo 10
Expression 2: ((((2+5)*7)+((9*3)*2))^2)
Answer:
25+7*93*2*+2^
9 in modulo 10
Expression 3: ((((2*3)*(4*6))*7)+(((7+8)+9)*((2+4)*((7+8)+9))))
Answer:
23*46*7*789++24+78+9+**+
4 in modulo 10
My code:
#include <iostream>
#include <string>
#include<sstream>
using namespace std;
class STACK {
private:
char *s;
int N;
public:
STACK(int maxN) {
s = new char[maxN];
N = 0;
}
int empty() const {
return N == 0;
}
void push(char item) {
s[N++] = item;
}
char pop() {
return s[--N];
}
};
int main() {
string infixExpr;
string postfixExpr = "";
cout << "Enter infix expression:" << endl;
cin >> infixExpr; //converting to postfix read from the input
int N = infixExpr.size(); //strncpy(a, infixExpr.c_str(), N);
STACK ops(N);
char ch;
for (int i = 0; i < N; i++) {
if (infixExpr[i] == ')')
{
ch = ops.pop();
postfixExpr.push_back(ch);
}
if ((infixExpr[i] == '+') || (infixExpr[i] == '*') || (infixExpr[i] == '^'))
ops.push(infixExpr[i]);
if ((infixExpr[i] >= '0') && (infixExpr[i] <= '9'))
{
//cout << infixExpr[i] << " ";
postfixExpr.push_back(infixExpr[i]);
}
}
cout <<"Answer :"<<endl;
cout <<postfixExpr <<endl; //evaluate post fix expression
N = postfixExpr.size();
STACK save(N);
int result;
int num;
int count = 0;
string temp = "";
for (int i = 0; i < N; i++) {
// cout << " Expr[i] " << postfixExpr[i] << endl;
if (postfixExpr[i] == '+')
save.push((save.pop() + save.pop()) % 10);
if (postfixExpr[i] == '*')
save.push((save.pop() * save.pop()) % 10);
if (postfixExpr[i] == '^') {
count = save.pop() - '0';
num = save.pop() - '0'; //cout << result << "- " <<"-" <<count<<endl;
result = 1;
for(int j = 1; j <= count; j++)
{
result = result * num;
result = result % 10;
}
stringstream convert;
convert << result;//add the value of Number to the characters in the stream
temp = convert.str();//set Result to the content of the stream
save.push(temp[0]);
}
if ((postfixExpr[i] >= '0') && (postfixExpr[i] <= '9'))
{
save.push(postfixExpr[i]);
}
}
cout << save.pop() <<" in module 10"<< endl;
return 1;
}

Related

Write a C++ program to find kernel in boolean expression

I am a college student, and I have a programming assignment asked us to find kernels in boolean expression. The document teacher provide has a sample pseudo code to guide us how to write a program. The pseudo code is as below.
// Kernel Algorithm
FindKernels(cube-free SOP expression F) // F: input Boolean function
{
K = empty; // K: list of kernel(s)
for(each variable x in F)
{
if(there are at least 2 cubes in F that have variable x)
{
let S = {cubes in F that have variable x in them};
let co = cube that results from intersection of all cubes
in S, this will be the product of just those literals that appear in
each of these cubes in S;
K = K ∪ FindKernels(F / co);
}
}
K = K ∪ F ;
return( K )
}
But I don.t know what is the meaning of the definition of "co". As what I understand S is those terms that have the variable X. Take "abc + abd + bcd = b(ac + ad + cd)" for example, S = {abc, abd, bcd}. But what is co??
I also write another program
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void find_kernels(vector<string> &terms);
bool eliminate_char(string &doing, char eliminate);
void eliminate_char_complete(vector<string> &terms, char eliminate);
int main()
{
string file_name;
vector<string> expression;
vector<string> expression_name;
string expression_temp, expression_name_temp, input_untruncated;
vector<vector<string>> terms;//break each expression into each term
here:
cout << "Please enter the file name that you want to load: ";
cin >> file_name;
ifstream load_file(file_name, ios::in);
if(!load_file)
{
cout << "The file you choose cannot be opened!\n";
goto here;
}
there:
cout << "Please enter the name of the output file: ";
cin >> file_name;
ofstream output_file(file_name, ios::out);
if(!output_file)
{
cout << "The file cannot be created!\n";
goto there;
}
while(load_file >> input_untruncated)
{
expression_name_temp = input_untruncated.substr(0, input_untruncated.find("="));
expression_temp = input_untruncated.substr(input_untruncated.find("=") + 1);
expression_name.push_back(expression_name_temp);
expression.push_back(expression_temp);
}
//start to truncate every terms
for(int i = 0 ; i < (int)expression.size() ; i++)
{
int j = 0;
int k = 0;//k >> last time location
vector<string> terms_temp_vector;
string terms_temp;
string expression_trans = expression[i];
while(j < (int)expression[i].size())
{
if(expression_trans[j] == '+' || expression_trans[j] == '-')
{
terms_temp = expression_trans.substr(k, j - k);
terms_temp_vector.push_back(terms_temp);
k = j + 1;
}
j++;
}
terms_temp = expression_trans.substr(k);
terms_temp_vector.push_back(terms_temp);
terms.push_back(terms_temp_vector);
}
/*for(int i = 0 ; i < (int)expression.size() ; i++)
{
cout << "expression_name: " << expression_name[i] << endl;
cout << expression[i] << endl;
cout << "terms: ";
for(int j = 0 ; j < (int)terms[i].size() ; j++)
{
cout << terms[i][j] << " ";
}
cout << endl;
}*/
cout << endl;
for(int i = 0 ; i < (int)expression.size() ; i++)
{
//output_file << expression_name[i] << endl;
//output_file << expression[i] << endl;
cout << "*";
while(terms[i].size() != 0)
{
find_kernels(terms[i]);
if(terms[i].size() != 0)
{
cout << "terms: ";
for(int j = 0 ; j < (int)terms[i].size() ; j++)
{
cout << terms[i][j] << " ";
}
cout << endl;
}
}
cout << endl;
}
/*for(int i = 0 ; i < (int)expression.size() ; i++)
{
cout << "expression_name: " << expression_name[i] << endl;
cout << expression[i] << endl;
cout << "terms: ";
for(int j = 0 ; j < (int)terms[i].size() ; j++)
{
cout << terms[i][j] << " ";
}
cout << endl;
}*/
return 0;
}
void find_kernels(vector<string> &terms)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, g = 0;
for(int i = 0 ; i < (int)terms.size() ; i++)
{
string terms_temp = terms[i];
for(int j = 0 ; j < (int)terms_temp.size() ; j++)
{
switch(terms_temp[j])
{
case 'a':
a++;
break;
case 'b':
b++;
break;
case 'c':
c++;
break;
case 'd':
d++;
break;
case 'e':
e++;
break;
case 'g':
g++;
break;
}
}
}
int compare[] = {a, b, c, d, e, g};
int biggest = 0;
char eliminate;
for(int i = 0 ; i < 6 ; i++)
{
if(compare[i] > biggest)
{
biggest = compare[i];
}
}
if(biggest == 1)
{
terms.erase(terms.begin(), terms.end());
return;
}
if(biggest == a)
{
eliminate = 'a';
eliminate_char_complete(terms, eliminate);
}
if(biggest == b)
{
eliminate = 'b';
eliminate_char_complete(terms, eliminate);
}
if(biggest == c)
{
eliminate = 'c';
eliminate_char_complete(terms, eliminate);
}
if(biggest == d)
{
eliminate = 'd';
eliminate_char_complete(terms, eliminate);
}
if(biggest == e)
{
eliminate = 'e';
eliminate_char_complete(terms, eliminate);
}
if(biggest == g)
{
eliminate = 'g';
eliminate_char_complete(terms, eliminate);
}
}
bool eliminate_char(string &doing, char eliminate)
{
for(int i = 0 ; i < (int)doing.size() ; i++)
{
if(doing[i] == eliminate)
{
doing.erase (i, 1);
return 1;
}
}
return 0;
}
void eliminate_char_complete(vector<string> &terms, char eliminate)//delete unrelated terms
{
for(int i = 0 ; i < (int)terms.size() ; i++)
{
if(!eliminate_char(terms[i], eliminate))
{
terms.erase(terms.begin() + i);
}
}
}
input file be like
F1=ace+bce+de+g
F2=abc+abd+bcd
I don't obey the pseudo code above.
First, I break them into single terms and push them into a two dimention vector called terms.
terms[expression number][how many terms in one expression]
Second, I call find_kernels. The founction calculate every letters appear how many times in one expression. ps: only a, b, c, d, e, g will appear.
Third, take out the letter that appear the most time. ex: a, ab, abc...
Then, eliminate them in every terms of the same expression. If a terms do not have those letters, then delete the term directly.
Continue doing the same thing....
However, the question is that if F1 is abc+abd+bcd, I should output ac+ad+cd c+d a+c a+d, but my program will output ac+ad+cd only, cause abc+abd+bcd = b(ac+ad+cd) >> next round ac+ad+cd. a, c, d all apear twice, so there are deleted together. Nothing left.
Any suggestion to my code or further explination of the pseudo code will be appreciate. Thank you.
In general you should be clear about the problem you want to solve and the applied definitions. Otherwise you will always run into severe troubles.
Here you want to calculate the kernels of a boolean expression given in SOP (sum over products form, e.g., abc+cde).
A kernel of a boolean expression F is a cube-free expression that results when you divide F by a single cube.
That single cube is called a co-kernel. (This is the co in the pseudo code)
From a cube-free expression you cannot factor out a single cube that leaves behind no remainder.
Examples
F=ae+be+cde+ab
Kernel Co-Kernel
{a,b,cd} e
{e,b} a
{e,cd} b
{ae,be, cde, ab} 1
F=ace+bce+de+g
Kernel Co-Kernel
{a,b} c
{ac, bc, d} e
As you can see the co-kernel is the variable that you eliminate plus all other common variables that occur in the cubes containing the variable.
To implement that you apply this procedure now recursicely for each variable and store all kernel you create. Essentially thats all!
Practically, for an implementation I would propose to use some more handy encoding of the terms and not strings. As your input seems to only single letter variables you can map it to single bits in uint64 (or even uint32 when only lower case is considered). This will give an straight forward implementation like that (thought, it is optimzed for simplicity not performance):
#include <iostream>
#include <vector>
#include <string>
#inlcude <set>
void read_terms();
uint64_t parse_term(string sterm);
void get_kernels(vector<uint64_t>& terms, vector<pair<vector<uint64_t>, uint64_t> >& kernels);
string format_kernel(vector<uint64_t>& kernel);
int main()
{
read_terms();
return 0;
}
/*
Convert a cube into a string
*/
string cube_to_string(uint64_t cube) {
string res;
char ch = 'a';
for (uint64_t curr = 1; curr <= cube && ch <= 'z'; curr <<= 1, ch++) {
if ((curr & cube) == 0) {
continue;
}
res += ch;
}
ch = 'A';
for (uint64_t curr = (1<<26); curr <= cube && ch <= 'Z'; curr <<= 1, ch++) {
if ((curr & cube) == 0) {
continue;
}
res += ch;
}
return res;
}
/*
Convert a kernel or some other SOP expression into into a string
*/
string format_kernel(vector<uint64_t>& kernel) {
string res = "";
for (uint64_t k : kernel) {
string t = cube_to_string(k) + "+";
if (t.size() > 1) {
res += t;
}
}
if (res.size() > 0) {
res.resize(res.size() - 1);
}
return res;
}
/*
Queries the expression from the stdin and triggers the kernel calculcation.
*/
void read_terms() {
cout << "Please enter the terms in SOP form (0 to end input):" << endl;
vector<uint64_t> terms;
vector<pair<vector<uint64_t>, uint64_t> > kernels;
string sterm;
cout << "Term: ";
while (cin >> sterm) {
if (sterm == "0") {
break;
}
cout << "Term: ";
terms.push_back(parse_term(sterm));
}
get_kernels(terms, kernels);
set<string> set_kernels;
for (pair<vector<uint64_t>, uint64_t>k : kernels) {
set_kernels.insert(format_kernel(k.first));
}
for (string k : set_kernels) {
cout << k << endl;
}
return;
}
/*
Convert a term given as string into a bit vector.
*/
uint64_t parse_term(string sterm) {
uint64_t res = 0;
for (char c : sterm) {
if (c >= 'a' && c <= 'z') {
res |= 1ull << uint64_t(c - 'a');
}
else if (c >= 'A' && c <= 'Z') {
res |= 1ull << uint64_t(c - 'A' + 26);
}
}
return res;
}
/*
Returns a bitvector having a for a each variable occuring in one or more of the cubes.
*/
uint64_t get_all_vars(vector<uint64_t>& terms) {
uint64_t res = 0;
for (uint64_t t : terms) {
res |= t;
}
return res;
}
/*
Returns a bitvector having a one for each variable that is shared between all cubes.
*/
uint64_t get_common_vars(vector<uint64_t>& terms) {
if( terms.size() == 0 ) {
return 0ull;
}
uint64_t res = terms[0];
for (uint64_t t : terms) {
res &= t;
}
return res;
}
/*
Divides all set variables from the cubes and returns then in a new vector.
*/
void div_terms(vector<uint64_t>& terms, uint64_t vars, vector<uint64_t>& result) {
result.resize(terms.size());
uint64_t rvars = vars ^ ~0ull; //flip all vars
for (size_t i = 0; i < terms.size(); i++) {
result[i] = terms[i] & rvars;
}
}
/*
Core calculation to get the kernels out of an expression.
*/
void get_kernels(vector<uint64_t>& terms, vector<pair<vector<uint64_t>, uint64_t> >& kernels ) {
uint64_t vars = get_all_vars(terms);
for (uint64_t curr = 1; curr <= vars; curr <<= 1) {
if ((curr & vars) == 0) {
continue;
}
vector<uint64_t> curr_terms, curr_div_terms;
for (uint64_t uterm : terms) {
if ((uterm & curr) != 0ull) {
curr_terms.push_back(uterm);
}
}
if (curr_terms.size() > 1) {
uint64_t new_kernel = 0ull;
uint64_t new_co = get_common_vars(curr_terms); // calculate the new co-kernel
div_terms(curr_terms, new_co, curr_div_terms);//divide cubes with new co-kernel
kernels.push_back(pair<vector<uint64_t>, uint64_t>(curr_div_terms, new_co));
get_kernels(curr_div_terms, kernels);
}
}
}
Especially the elimination of kernels that occur several times is not very efficient, as it just happens at the end. Usually you would do this earlier and prevent multiple calculation.
This implementation takes the inputs from the stdin and writes the results to the stdout. So you might change it for using files when using it as your homework.
Thought other implementations like counting the number of occurences and making use out of that is also possible.

Converting HEX to DEC [duplicate]

This question already has answers here:
C++: Converting Hexadecimal to Decimal
(11 answers)
Closed 2 years ago.
I'm trying to use a C++ program to convert a hexadecimal value into a decimal value. Just can't come up with a working code.
This is the best thing I have come up with:
int main () {
string link;
string hex_code;
int dec_code;
int i;
int n = 6;
int num;
int hex;
cout << "Insert 1 of the HEX characters at a time:";
for (i = 0; i < n; i++) {
cin >> hex_code;
}
for (i = 0; i < n; i++) {
if (hex_code == "A") {
hex_code = 10;
}
else if (hex_code == "B") {
hex_code = 11;
}
else if (hex_code == "C") {
hex_code = 12;
}
else if (hex_code == "D") {
hex_code = 13;
}
else if (hex_code == "E") {
hex_code = 14;
}
else if (hex_code == "F") {
hex_code = 15;
}
else {
hex_code = hex_code;
}
num = hex * pow (16, i);
}
for (i = 0; i < n; i++) {
dec_code = dec_code + num;
}
cout << dec_code;
return 0;
}
Any help/feddback/opinions are welcome.
Edit: Thank you for all your help. Found the code I tryed to create, but failed, here: https://stackoverflow.com/a/27334556/13615474
There is a hex manipulator in iomanip library of C++
cout << "Insert 1 of the HEX characters at a time:";
for (i = 0; i < n; i++) {
int hexcode;
std::cin >> std::hex >> hexcode;
std::cout << hexcode << std::endl;
}
This would print decimal equivalent of given hex code
Hex to decimal conversion can be performed by reading the input number as a character array and performing the conversion arithmetic on each character.
Here is a working example for converting hexadecimal into decimal:
// File name: HexToDec.cpp
#include <iostream>
#include <cstring>
using namespace std;
int hexToDec(char hexNumber[]) {
int decimalNumber = 0;
int len = strlen(hexNumber);
for (int base = 1, i=(len-1); i>=0; i--, base *= 16) {
// Get the hex digit in upper case
char digit = toupper(hexNumber[i]);
if ( digit >= '0' && digit <='9' ) {
decimalNumber += (digit - 48)*base;
}
else if ( digit >='A' && digit <='F' ) {
decimalNumber += (digit - 55)*base;
}
}
return decimalNumber;
}
int main() {
char hexNumber[80];
// Read the hexadecimal number as a character array
cout << "Enter hexadecimal number: ";
cin >> hexNumber;
cout << hexNumber << " in decimal format = " << hexToDec(hexNumber) << "\n";
return 0;
}
Output:
Enter hexadecimal number: DEC
DEC in decimal format = 3564
More information:
https://www.geeksforgeeks.org/program-for-hexadecimal-to-decimal/
Here is a simple code fragment using a lookup table:
char c;
static const char hex_to_decimal[] = "0123456789ABCDEF";
std::cin >> c;
int decimal = 0;
for (decimal = 0; decimal < sizeof(hex_to_decimal) - 1; ++decimal)
{
if (hex_to_decimal[i] == c)
{
break;
}
}
Another conversion method:
std::cin >> c;
int decimal;
if (is_digit(c))
{
decimal = c - '0';
}
else
{
decimal = 10 + c - 'A';
}
The above code fragment assumes that the encoding has 'A'...'F' contiguous.
The first example is more portable.

C++ binary input as a string to a decimal

I am trying to write a code that takes a binary number input as a string and will only accept 1's or 0's if not there should be an error message displayed. Then it should go through a loop digit by digit to convert the binary number as a string to decimal. I cant seem to get it right I have the fact that it will only accept 1's or 0's correct. But then when it gets into the calculations something messes up and I cant seem to get it correct. Currently this is the closest I believe I have to getting it working. could anyone give me a hint or help me with what i am doing wrong?
#include <iostream>
#include <string>
using namespace std;
string a;
int input();
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] = '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + pow(x,2);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
int input()
{
int x, x2, count, repeat = 0;
while (repeat == 0)
{
cout << "Enter a string representing a binary number => ";
cin >> a;
count = a.length();
for (x = 0; x < count; x++)
{
if (a[x] != '0' && a[x] != '1')
{
cout << a << " is not a string representing a binary number>" << endl;
repeat = 0;
break;
}
else
repeat = 1;
}
}
return 0;
}
I don't think that pow suits for integer calculation. In this case, you can use shift operator.
a[i] = '1' sets the value of a[i] to '1' and return '1', which is always true.
You shouldn't access a[length], which should be meaningless.
fixed code:
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length - 1; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] == '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + (1 << x);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
I would use this approach...
#include <iostream>
using namespace std;
int main()
{
string str{ "10110011" }; // max length can be sizeof(int) X 8
int dec = 0, mask = 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str[i] == '1') {
dec |= mask;
}
mask <<= 1;
}
cout << "Decimal number is: " << dec;
// system("pause");
return 0;
}
Works for binary strings up to 32 bits. Swap out integer for long to get 64 bits.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string getBinaryString(int value, unsigned int length, bool reverse) {
string output = string(length, '0');
if (!reverse) {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << i)) != 0) {
output[i] = '1';
}
}
}
else {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << (length - i - 1))) != 0) {
output[i] = '1';
}
}
}
return output;
}
unsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {
unsigned long val = 0;
unsigned int offset = 0;
if (lsbindex > msbindex) {
size_t length = lsbindex - msbindex;
for (size_t i = msbindex; i <= lsbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << (length - offset));
}
}
}
else { //lsbindex < msbindex
for (size_t i = lsbindex; i <= msbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << offset);
}
}
}
return val;
}
int main() {
int value = 23;
cout << value << ": " << getBinaryString(value, 5, false) << endl;
string str = "01011";
cout << str << ": " << getInteger(str, 1, 3) << endl;
}
I see multiple misstages in your code.
Your for-loop should start at i = length - 1 instead of i = length.
a[i] = '1' sets a[i] to '1' and does not compare it.
pow(x,2) means and not . pow is also not designed for integer operations. Use 2*2*... or 1<<e instead.
Also there are shorter ways to achieve it. Here is a example how I would do it:
std::size_t fromBinaryString(const std::string &str)
{
std::size_t result = 0;
for (std::size_t i = 0; i < str.size(); ++i)
{
// '0' - '0' == 0 and '1' - '0' == 1.
// If you don't want to assume that, you can use if or switch
result = (result << 1) + str[i] - '0';
}
return result;
}

C++ Error: Line 1440 Expression: string subscript out of range

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.

Palindrome Function

I need to rewrite the program to use a function isPalindrome. It needs to input a 5 digit integer and return a boolean (true if it is a palindrome, false if it is not), and it cannot contain any cout statements. I am not sure how I would do this without a cout function. Here is my code:
#include <iostream>
using namespace std;
int main()
{
int number, digit1, digit2, digit3, digit4, digit5;
cout << "\nEnter a 5-digit integer: ";
cin >> number;
//Break down input number into individual digits:
digit1 = number / 10000;
digit2 = number % 10000 / 1000;
digit3 = number % 10000 / 100;
digit4 = number % 10000 / 10;
digit5 = number % 10;
if ( digit1 == digit5 && digit2 == digit4 )
cout << number <<" is a palindrome.\n";
else
cout << number << " is not a palindrome.\n";
return 0;
}
int isPalindrome ()
{
}
This should help get you started (without ruining too much of the fun)
int main(){
//accept integer input using cin
if(isPalindrome(input))
cout << "yaay!";
else
cout << "nooouuu!";
}
bool isPalindrome (int input)
{
//test things here
return ( digit1 == digit5 && digit2 == digit4 )
// ^ returns true if condition satisfied
}
Additionally, your way of separating out the digits is incorrect. It should be:
digit1 = number/10000 % 10;
digit2 = number/1000 % 10;
digit3 = number/100 % 10;
digit4 = number/10 % 10;
digit5 = number % 10;
Ofcourse, the above should actually be in a loop.
It doesn't have to be specified how many digits does the number contain. You can try something like this:
bool isPalindrome(int number) {
int reverse = 0, copy = number;
while(copy != 0) {
reverse = reverse*10 + copy%10;
copy /= 10;
}
return number == reverse;
}
string s;
cout<<"\nEnter a string : " ;
cin>>s;
int length = s.length();
char* arr = new char();
int k = length;
for(int i = 0 ; i <= length ; i++)
{
arr[i] = s[k];
k -= 1;
}
if(!palindrome(s, arr, length))
{
cout<<"\nNot Palindrome\n";
}
else
{
cout<<"\nPalindrome\n";
}
}
bool palindrome(string& s, char* arr, int length)
{
int j = 0;
for(int i = 1 ; i <= length; i++)
{
if(arr[i]!= s[j])
{
return false;
}
j++;
}
return true;
}