I have input such as:
10000000000000-1=
and
AAAAABBBBBCCCCCDDDDDEEEEEFFFFF-ABCDEF0123456789ABCDEF=
I need to convert the hexadecimal strings digit by digit into decimal and keep track if I need to borrow. I'm not sure how to adjust the value of operand 1 when a borrow occurs. Such as in the first line when you have to borrow 13 times.
Currently, I have
#include <iostream>
#include <fstream>
using namespace std;
string decimalToHex(int);
void subtraction(string, string)
int hexadecimalToDecimal(char hexVal);
int fullSubtractor(int tempOp1, int tempOp2)
int main()
{
ifstream myFile;
string l1, l2, l3, l4, l5, l6, l7, l8; //lines
string l1op1, l1op2, l2op1, l2op2, l3op1, l3op2, l4op1, l4op2, l5op1, l5op2, l6op1, l6op2, l7op1, l7op2, l8op1, l8op2; //parsed operators
myFile.open("data.txt");
if (myFile.is_open()) //check if file opened
{
cout << "File opened successfully. " << endl;
}
else
{
cerr << "File failed to open." << endl;
return 1;
}
while (!myFile.eof())
{
myFile >> l6 >> l7; //read in line by line
}
l6op1 = l6.substr(0, l6.find("-"));
l6op2 = l6.substr(l6.find("-") + 1);
l6op2 = l6op2.substr(0, l6op2.length() - 1);
std::string l6op2_zeros = std::string((l6op1.length()) - l6op2.length(), '0') + l6op2;
cout << l6; // << subtraction(l6op1, l6op2_zeros) << endl;
subtraction(l6op1, l6op2_zeros);
cout << endl;
l7op1 = l7.substr(0, l7.find("-"));
l7op2 = l7.substr(l7.find("-") + 1);
l7op2 = l7op2.substr(0, l7op2.length() - 1);
std::string l7op2_zeros = std::string((l7op1.length()) - l7op2.length(), '0') + l7op2; //appends zeros to front of second operand to make it same length as operand 1
cout << l7; // << subtraction(l7op1, l7op2) << endl;
subtraction(l7op1, l7op2_zeros);
cout << endl;
myFile.close();
return 0;
}
int fullSubtractor(int tempOp1, int tempOp2)
{
static int borrow;
int result = 0;
if ((tempOp1 < tempOp2) || ((tempOp1 == 0) && (borrow == 1)))
{
tempOp1 += 16;
result = tempOp1 - borrow - tempOp2;
borrow = 1;
}
else
{
result = tempOp1 - tempOp2;
borrow = 0;
}
return result;
}
void subtraction(string op1, string op2)
{
string result;
int tempDifference = 0, tempHex = 0;
int j = op2.length() - 1;
for (int i = op1.length() - 1; i >= 0; i--)
{
int temp1 = hexadecimalToDecimal(op1[i]);
int temp2 = hexadecimalToDecimal(op2[j]);
tempHex = fullSubtractor(temp1, temp2);
result = decimalToHex(tempHex) + result;
cout << result << " ";
j--;
}
cout << result << endl;
//return result;
}
int hexadecimalToDecimal(char hexVal)
{
int base = 1;
int dec_val = 0;
if (hexVal >= '0' && hexVal <= '9')
{
dec_val += (hexVal - 48) * base;
base *= 16;
}
else if (hexVal >= 'A' && hexVal <= 'F')
{
dec_val += (hexVal - 55) * base;
// incrementing base by power
base *= 16;
}
return dec_val;
}
string decimalToHex(int decNum)
{
stringstream ss;
ss << hex << decNum;
string hexNum(ss.str());
//cout << hexNum << endl;
return hexNum;
}
Related
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;
}
Sorry this is my first time use stackoverflow.
I dont kow where is the mistake in my code.
Output that i want:
-1+3-5+7-9+11-13+15
RESULT : 8
But Output that is shown
-1+3-5+7-9+11-13+15
RESULT : 10
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
cout << "+";
}
if (i == 1) {
sign = 1;
cout << "-";
}
x = sign * (2 * i - 1);
cout << x;
S = S + x;
}
cout << "\n Result:" << S;
}
problem is in the if condition block where you check i==1
in that loop you are making sign=1 that should be sign=-1
How about improving the logic like following?
#include <iostream>
using namespace std;
int main()
{
int i;
bool sign = true; // signed/minus = true, non-signed/plus = false
int ans = 0;
for( i=1; i<=15; i=i+2){
if( sign == true){
cout << "-" << i;
ans = ans - i;
}
else {
cout << "+" << i;
ans = ans + i;
}
sign = !sign;
}
cout << endl << "RESULT : " << ans << endl;
return 0;
}
Try this code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
else
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
// cout << "+";
}
//else
if (i == 1) {
sign = -1;
//cout << "-";
}
x = sign * (2 * i - 1);
cout <<"\n"<<x;
S = S + x;
//cout<<"S is \n"<<S;
}
cout << "\n Result:" << S;
}
You have put wrong sign when i==1
The problem is that you're starting the calculation with a positive sign (but you're lying to yourself by printing "-").
You can simplify the code and don't need to mess around with pow if you make the obervation that
pow(-1, k) == -1 * pow(-1, k-1)
Starting at pow(-1,0) (that is, 1), you can write:
int main(int argc, char* argv[])
{
int sign = 1; // sign will always hold pow(-1, i).
int sum = 0;
for (int i = 1; i <= 8; i++)
{
sign *= -1;
if (sign > 0) // Since sign starts at -1, we know that i > 1 here
{
std::cout << "+";
}
int term = sign * (2 * i - 1);
std::cout << term;
sum += term;
}
std::cout << " = " << sum << std::endl;
}
I am VERY new to programming so this is a very 'messy'/'dirty' code.
Situation is, if I got 2 strings
e.g.
ASDFGHJKL and PFUYASD
I would like to output their positions where letters match like this:
"Match found at 0 of Strand 1 and 6 of Strand 2"
Conditions:
They must match upto three side by side characters. (the reason why the F isn't considered in the example)
Strand 1 is longer than Strand 2
So I got this code that works for finding match up to second letter. This works fine
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
int x = 0;
int y = 0;
int str1match;
int str2match;
string str1;
string str2;
cout << "string1\n";
cin >> str1;
cout << "string2\n";
cin >> str2;
int length = str1.length();
startagain:
int pos = str2.find(str1[x]);
if ((pos >= 0) && (x<length))
{
x = x + 1;
pos = pos + 1;
if (str1[x] == str2[pos])
{
x = x + 1;
pos = pos + 1;
if (str1[x] == str2[pos])
{
str1match = x - 2;
str2match = pos - 2;
cout << "Match at " << str1match << " of Strand 1 and at " << str2match << " of Strand 2";
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else if ((pos == -1) && (x<length))
{
x = x + 1;
goto startagain;
}
else
{
cout << "Match not found";
}
_getch();
return 0;
}
But I needed the code to find match until atleast 3rd letter so i thought just by adding more nested loop it will work but it doesn't. here's is the code that doesn't work:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
int x = 0;
int str1match, str2match;
string strand1, strand2;
cout << "Enter Strand 1:\n";
cin >> strand1;
cout << "Enter Strand 2:\n";
cin >> strand2;
int length = strand1.length();
startagain:
int pos = strand2.find(strand1[x]);
if ((pos >= 0) && (x < length))
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
str1match = x - 3;
str2match = pos - 3;
cout << "Match at " << str1match << "of Strand 1 and at " << str2match << "of Strand 2";
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else if ((pos == -1) && (x < length))
{
x = x + 1;
goto startagain;
}
else
{
cout << "Match not found";
}
_getch();
return 0;
}
bool found = false;
for(int i=0;i<strand1.size()-2;i++){
int pos = strand2.find(strand1.substr(i,3));
if(pos != string::npos){
found = true;
cout << "match at " << i << "in 1 with " << pos << " in 2" << '\n';
break;
}
}
if (!found) cout << "No match";
string.substr finds a substring starting from i
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.**
I'm trying to create a roman calculator that reads from a file. I'm struggling to figure out how to add characters to a string. I would like a new character to be added with no spaces after each iteration of a loop this would be used when the program is writing the answer.
I've tried this.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
string convert_to_Roman(int num)
{
string c;
while (num>0)
{
string c;
if (num >= 1000)
{
num = num - 1000;
return c='M';
}
else if (num >= 500 && num<1000)
{
num = num -500;
return c = 'D';
}
else if (num >= 100 && num<500)
{
num = num -100;
return c= 'C';
}
else if (num >= 50 && num<100)
{
num = num - 50;
return c = 'L';
}
else if (num >= 10 && num<50)
{
num = num - 10;
return c = 'X';
}
else if (num >= 5 && num<10)
{
num = num - 5;
return c = 'V';
}
else if (num<5)
{
num = num - 1;
return c = 'I';
}
c +=c;
//cout<<"answer= "<< + answer<<endl;
}
cout << c;
}
int convert_from_Roman(string & s)
{
int num=0;
int length; //length of string
length = s.length();
for (int i = 0; i < length; i++)
{
char c = s[i];
int digit;
if (c == 'M')
{
return num = 1000;
}
else if (c == 'D')
{
return num = 500;
}
else if (c == 'C')
{
return num = 100;
}
else if (c == 'L')
{
return num = 50;
}
else if (c == 'X')
{
return num = 10;
}
else if (c == 'V')
{
return num = 5;
}
else if (c == 'I')
{
return num = 1;
}
else
{
cout << "invalid entry" << endl;
continue;
}
num += num;
}
cout<<num<<endl;
}
void print_Result(/* figure out the calling sequence */)
{
// fill in your code
}
// Note the call by reference parameters:
string finalAnswer()
{
string operand1, operand2;
char oper;
cout << "enter operation: " << endl;
cin >> operand1 >> operand2 >> oper;
int value1, value2, answer;
value1 = convert_from_Roman(operand1);
value2 = convert_from_Roman(operand2);
switch (oper)
{
case '+':
{
answer = value1 + value2;
break;
}
case '-':
{
answer = value1 - value2;
break;
}
case '*':
{
answer = value1*value2;
break;
}
case '/':
{
answer = value1 / value2;
break;
}
default:
{
cout << "bad operator : " << oper << endl;
return;
}
string answerInRoman = convert_to_Roman(answer);
return answerInRoman;
cout << "answer= " << answerInRoman << " (" << answer << ") " << endl;
}
You can simply use concatenation like so.
char addThis;
string toThis;
addThis = 'I';
toThis = "V";
toThis += addThis;
or
toThis = toThis + addThis;
If you want to place the number somewhere other than the end of a string, you can access the elements of a string like an array toThis[0] is equal to 'V'.
If you are not using std::string as mentioned below, this can be done with a dynamic character array and an insert method that resizes the array properly as follows:
#include <iostream>
using namespace std;
void addCharToArray(char * & array, int physicalSize, int & logicalSize, char addThis)
{
char * tempPtr;
if (physicalSize == logicalSize)
{
tempPtr = new char[logicalSize + physicalSize];
for (int i = 0; i < logicalSize; i++)
{
tempPtr[i] = array[i];
}
delete [] array;
array = tempPtr;
}
array[logicalSize] = addThis;
logicalSize++;
}
int main()
{
char addThis = 'I';
char * toThis;
int physicalSize = 1;
int logicalSize = 0;
toThis = new char[physicalSize];
toThis[0] = 'V';
logicalSize++;
//when adding into the array, you must perform a check to see if you must add memory
addCharToArray(toThis, physicalSize, logicalSize, addThis);
for (int i = 0; i < logicalSize; i++)
{
cout << toThis[i];
}
cout << endl;
return 0;
}