-
April 23rd, 2011, 10:36 AM
#1
adding digits from a char array to an int
hi! im writing a console calculator that so far only supports addition. the user should be able to enter something like: 3 + 6
and get 9 returned
my troubles are that i dont understand how to seperate the numbers and store them in int variables so i can add them. i have 3 functions in this program.
findSign which locates the + sign
removeSpace which gets rid of all the spaces in the equation
add which actually adds all the numbers
heres my code
Code:
#include<iostream>
#include<cstring>
using std::cout;
using std::cin;
using std::endl;
int findSign(char expression[], int length);
char* removeSpace(char* string, int length, char* spaceless, int& spaceCounter);
int add(char equation[], int loc, int length);
int main(void)
{
//get equation from user
const int max = 50;
char entered[max];
cin.getline(entered, 50, '\n');
int len = strlen(entered);
char* expression = new char[len];
int length = sizeof expression/sizeof expression[0];
//get rid of all spaces
int spaceCounter = 0;
char* equation = new char[length];
equation = removeSpace(expression, length, equation, spaceCounter);
//find the + sign and the total
int loc = findSign(equation, length);
int total = add(equation, loc, length);
cout << total;
//clear memory and close the program
delete[] expression;
delete[] equation;
expression = 0;
equation = 0;
cout << endl;
return 0;
}
char* removeSpace(char* string, int length, char* spaceless, int& spaceCounter)
{
//remove all the spaces by adding all characters that arent spaces to the spaceless array
for (int i = 0; i < length; i++)
{
if (string[i] == ' ')
continue;
else
{
spaceless[spaceCounter] = string[i];
spaceCounter++;
}
}
return spaceless;
}
int findSign(char expression[], int length)
{
//locate the + sign
int location = 0;
for (int i = 0; i < length; i++)
{
if (expression[i] == '+')
{
location = i;
}
}
return location;
}
int add(char equation[], int loc, int length)
{
//add the two numbers
int num1 = 0, num2 = 0;
int i = 0;
for (; i < loc; i++)
{
num1 += (equation[i] - 48); //subtract 48 to convert from ascii to a decimal
cout << equation[i] << endl;
}
for (; i < length - 1; i++)
{
num2 += (equation[i] - 48); //subtract 48 to convert from ascii to a decimal
cout << equation[i] << endl;
}
return num1 + num2;
}
-
April 23rd, 2011, 10:59 AM
#2
Re: adding digits from a char array to an int
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|