hi, I am trying to make a variable equation solver using DEV-C++. I just need to know how to get C++ to solve an equation inputed by the user. So you input something like 1+1 and i need it to solve the problem and output the answer. heres an example:

#include<iostream>
using namespace std;
int main (char argc)
{
    string n1;
    cin >> n1; // i input 1+1
    int n2;
    solve n1 = n2;
    cout << n2 << endl; // it outputs 2
}

thanks

/**
 * Numerics.cpp
 */
#ifndef NUMERICS
#define NUMERICS

#include <sstream>
#include <string>

using std::stringstream;
using std::string;

/**
 * Convenience class for enabling easy
 * conversions between strings and primitive types.
 *
 * This class is not meant to support non-primitive types,
 * but it should if target class Type has istream and ostream
 * operators overloaded.
 */
namespace Numerics{

	template<class T>
	class Numerical{
	
		private:
			T number;

		public:
			Numerical(T value = 0) : number(value){}
			Numerical(const string& arg){
				const_cast<Numerical&>(*this)(arg);
			}

			/**
			 * Attempts to assign the argument value to the value
			 * of this Object's type.
			 * If the value is invalid, nothing happens.
			 */
			string operator()(const string& arg){
				stringstream ss (stringstream::in | stringstream::out);
				try{
					ss << arg;
					ss >> number;
				}catch(...){
					// currently unsupported
				}
				return ss.str();
			}

			/**
			 * Attempts to assign the argument value to the value of
			 * this Object's type.
			 */
			T operator()(T value){
				return (number = value);
			}

			/**
			 * Returns a string representation of this Object's number
			 */
			string getString(){
				stringstream ss (stringstream::in | stringstream::out);
				ss << number;
				return ss.str();
			}

			/**
			 * Returns a copy of this Object's number
			 */
			T getValue(){
				return number;
			}

			/**
			 * Extraction operator used to return the underlying value
			 * during operations assosciated with primitive types.
			 */
			operator T& (){
				return number;
			}

			/**
			 * const version of the above operator. Returns a copy
			 * of this Object's number.
			 */
			operator T () const{
				return number;
			}
	};

	/* Some meaningful typedefs for Numerical types */
	typedef Numerical<short> Short;
	typedef Numerical<unsigned short> U_Short;
	typedef Numerical<int> Integer;
	typedef Numerical<unsigned int> U_Integer;
	typedef Numerical<double> Double;
	typedef Numerical<float> Float;
	typedef Numerical<char> Byte;
	typedef Numerical<unsigned char> U_Byte;
	typedef Numerical<wchar_t> Wide_Byte;
	typedef Numerical<long int> Long;
	typedef Numerical<unsigned long int> U_Long;

	/* For non-standard types, like __int8, __int16, __int32, and __int64 */
	#ifdef ALLOW_NONSTANDARD_PRIMITIVE_TYPES

		#if (ALLOW_NONSTANDARD_PRIMITIVE_TYPES == 0x01)
			typedef Numerical < __int8 > __Int8;
			typedef Numerical < unsigned __int8 > U___Int8;
			typedef Numerical < __int16 > __Int16;
			typedef Numerical < unsigned __int16 > U___Int16;
			typedef Numerical < __int32 > __Int32;
			typedef Numerical < unsigned __int32 > U___Int32;
			typedef Numerical < __int64 > __Int64;
			typedef Numerical < unsigned __int64 > U___Int64;
		#endif

	#endif
}

#endif


////////////////////////////////////

/**
 * EquationSolver.h
 */

#ifndef EQUATION_SOLVER_H
#define EQUATION_SOLVER_H

#include <string>
#include <vector>

using std::string;
using std::vector;

namespace EquationHelper{

	class EquationSolver{
		private: 
			EquationSolver();
			static string doOperation(const string&, char, const string&);
			static void correctedString(string&);
			static void removeSpaces(string&);
			static string parse(const string&);
			static bool isSolvable(const string&);
			static void calculate(vector<string>&, vector<char>&, const string&);

		public:
			static string solve(const string&, int = 50);
	};
}
#include "EquationSolver.cpp"

#endif

////////////////////////////////

/**
 * EquationSolver.cpp
 */

#ifdef EQUATION_SOLVER_H

#include <iostream>
#include <cmath>
#include <vector>
#include <string>
#include "Numerics.cpp"

using namespace EquationHelper;
using namespace Numerics;
using std::size_t;
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::ios;

typedef EquationSolver ES;

/**
 * Private constructor - does nothing.
 */
ES::EquationSolver(){}

/**
 * Performs the specified operation against the
 * argument strings. The operation is dependant on
 * the value of op.
 */
string ES::doOperation(const string& lhs, char op, const string& rhs){
	
	Double bdLhs = lhs;
	Double bdRhs = rhs;
	Double temp;
	switch(op){
		case '^':
			temp( pow( bdLhs, bdRhs ) );
			break;
		case '*':
			temp( bdLhs * bdRhs );
			break;
		case '/':
			temp( bdLhs / bdRhs );
			break;
		case '+':
			temp( bdLhs + bdRhs );
			break;
		case '%':
			temp( fmod(bdLhs, bdRhs) );
			break;
	}
	return temp.getString();
}

/**
 * Returns the string with its enclosing paranthesis
 * stripped from it.
 */
void ES::correctedString(string& arg){
	
	size_t pos1 = arg.find_first_of("(");
	size_t pos2 = arg.find_last_of(")");

	if(pos1 >= 0 && pos1 < arg.length() && pos2 >= 0 && pos2 <= arg.length())
		arg[pos1] = arg[pos2] = ' ';
}

/**
 * Remove spaces from the argument string.
 */
void ES::removeSpaces(string& argu){

	string temp = "";
	for(size_t i = 0; i < argu.length(); i++)
		if(argu[i] != ' ')
			temp += argu[i];
	argu = temp;
}

/**
 * The brains of the program.
 * Solves expressions by using recursion for complex expressions.
 */
string ES::parse(const string& param){
	
	string expression = param;
	correctedString(expression);
	removeSpaces(expression);
	string finalExpression = "";

	bool operatorEncountered = true;
	for(size_t i = 0; i < expression.length(); i++){
		if(expression[i] == '('){	
			string placeHolder = "(";	
			int valuesCounted = 1;		
			operatorEncountered = false;
			for(size_t j = i + 1; valuesCounted != 0; j++){	
				if(expression[j] == '(')	
					valuesCounted++;
				else if(expression[j] == ')')	
					valuesCounted--;

				placeHolder += expression[j];
			}

			string evaluatedString = parse(placeHolder); 
			finalExpression += evaluatedString;	
			i += (placeHolder.length() - 1); 
		}else{
			if(expression[i] == '-' && operatorEncountered == false)
				finalExpression += '+';

			finalExpression += expression[i];
			if((expression[i] == '+'
			|| expression[i] == '/'
			|| expression[i] == '^'
			|| expression[i] == '*'
			|| expression[i] == '%'
			|| expression[i] == '-'))
				operatorEncountered = true;
			else if(expression[i] != ' ')
				operatorEncountered = false;
		}
	}

	removeSpaces(finalExpression);	
	string perfectExpression = "";	

	for(size_t i = 0; i < finalExpression.length(); i++){	
		if((i + 1) < finalExpression.length())	
			if(finalExpression[i] == '-' && finalExpression[i + 1] == '-')
				i += 2;																	
		perfectExpression += finalExpression[i];	
	}
	finalExpression = perfectExpression;

	vector<string> totalNumbers;
	vector<char> totalOperations;	
	cout << finalExpression << endl;	

	for(size_t i = 0; i < finalExpression.length(); i++){
		if(finalExpression[i] >= '0' && finalExpression[i] <= '9'
		|| finalExpression[i] == '-' || finalExpression[i] == '.'){	
			string temp = "";	//
			for(size_t j = i; j < finalExpression.length(); j++){	
				if(finalExpression[j] >= '0' && finalExpression[j] <= '9'
				|| finalExpression[j] == '-' || finalExpression[j] == '.'){
						temp += finalExpression[j];	
				}else break;
			}
			totalNumbers.push_back(temp);	
			i += temp.length() == 0 ? 0 : (temp.length() - 1);	
		}else if(finalExpression[i] == '*'
			  || finalExpression[i] == '/'
			  || finalExpression[i] == '^'
			  || finalExpression[i] == '+'
			  || finalExpression[i] == '%'
			  ){
			totalOperations.push_back(finalExpression[i]);
		}
	}

	ES::calculate(totalNumbers, totalOperations, "^");
	ES::calculate(totalNumbers, totalOperations, "*/%");
	ES::calculate(totalNumbers, totalOperations, "+");

	return totalNumbers[0];
}

/**
 * Calculates the numbers in the first vector using the operands in the 2nd vector,
 * based on the expressions allowed which are determined by the string argument.
 */
void ES::calculate(vector<string>& totalNumbers, vector<char>& totalOperations, 
				   const string& arg){

	for(int i = 0; i < static_cast<int>(totalOperations.size()); i++){
		if( arg.find(totalOperations[i]) != arg.npos){
			totalNumbers[i] = doOperation(totalNumbers[i], totalOperations[i], totalNumbers[i + 1]);
			
			size_t oldNumberLength = totalNumbers.size();
			size_t oldOperatorLength = totalOperations.size();
			size_t nextNumberLength = oldNumberLength - 1;
			size_t nextOperatorLength = oldOperatorLength - 1;
			size_t sCount = 0;
			size_t oCount = 0;
			vector<string> temp1 ( nextNumberLength );
			vector<char> temp2 ( nextOperatorLength );
			
			for(size_t j = 0; j < oldNumberLength; j++){
				if(j != static_cast<int>(i + 1)){
					temp1[sCount++] = totalNumbers[j];
				}
				if(j != i && j < oldOperatorLength){
					temp2[oCount++] = totalOperations[j];
				}
			}
			totalNumbers = temp1;
			totalOperations = temp2;

			i--;
		}
	}
}

/**
 * Returns true if the equation is solvable (not really),
 * returns false otherwise.
 *
 * This function is truly a misnomer, because more restrictions
 * should be put in place.
 */
bool ES::isSolvable(const string& eq){
	
	int paranthesisCount = 0;
	for(size_t i = 0; i < eq.length(); i++){
		if(eq[i] == '(')	
			paranthesisCount++;	
		else if(eq[i] == ')')	
			paranthesisCount--;	

		if(paranthesisCount < 0)
			return false;
	}
	return paranthesisCount == 0;
}

/**
 * An attempt to solve a string-expression, given
 * a precision value.
 */
string ES::solve(const string& eq, int prec){

	if(isSolvable(eq)){

		stringstream ss (stringstream::in | stringstream::out);
		cout << eq << endl;
		string value;

		value += '(';
		value += eq;
		value += ')';
		
		ss.setf(0, ios::floatfield);
		ss.precision(prec);
		ss << parse(value);

		return ss.str();
	}else return "";
}

#endif

////////////////////////////////////

/**
 * DriverProgram.cpp
 */

/****************************************
 * @Author: Mark Alexander Edwards Jr.
 *
 * This program uses a utility class to solve
 * complex equations represented by string 
 * expressions
 ****************************************/
#include <iostream>
#include <ctime>
#include <string>
#include "Numerics.cpp"
#include "EquationSolver.h"

using std::cin;
using std::cout;
using std::endl;
using std::flush;
using std::string;
using namespace Numerics;
using namespace EquationHelper;

int main(){
	
	cout << ES::solve("5 + 3 * (8 - 4)") << endl << endl;
	cout << ES::solve("12 / (3 * 4) + 5") << endl << endl;

	while(true){
		cout << "Enter an equation you would \nlike to solve (enter 'exit' to quit): " << flush;
		try{
			string temp;
			getline(cin, temp);
			if(temp.compare("exit") == 0) exit(0);
			clock_t t1 = clock();
			cout << "Answer: " + ES::solve(temp, 4) << endl;
			clock_t t2 = clock();
			cout << "\nTime taken to calculate value: " <<
				(t2-t1) << " Clock cycles" <<endl;
		}catch(...){
			cout << "Invalid expression! Please try again!" << endl;
		}
	}

	cin.ignore();
	cin.get();
	return 0;
}

And I did not write it lol I found it here!

that code that you posted, sergent, for some reason wont work in my compiler. there are 9 errors that i cant fix. are you sure that that was written for DEV-C++?

Well, it is mostly standard C++. I use codeblocks and it works there. Can you please post the errors you get. And if it is your homework like raptr said then do it yourself! If you are doing it for fun you can use the code!

First, understand how recursive-descent parsers work. That is the fundamental method to build a calculator or numerical/mathematical expression evaluator.

forgive me but i forgot to clarify one thing, i need the calculator to be able to calculate more than 2 numbers. it would be best if the calculator can calculate as many numbers you want. I also need it to work with ( and ) thanks

Let me just warn you that I am a very early beginner in c++. So I searched recursive descent parser and I have know idea how to put that into code.

C++ or otherwise, are you familiar with the following concepts?
+ Linked lists
+ Stack data structure
+ Binary tree structure
+ Parsing tokens from a string
If not, you may be taking on an effort that's more complex than you're ready for.

The basic problem is: for an arbitrary expression entered by a user, you need to tokenize it (recognize what's a number, what's an operator, what's a function, and what's a grouping-via-parentheses), build a parse-tree (creates a structure which indicates which operations should be performed in which order ... and in the process determine whether the input makes sense and generate an error if it doesn't), and then evaluate the parse-tree to arrive at an answer.

This really is the same basic functionality as writing a computer-language interpreter (although in this more limited case, only the part that deals with arithmetic). Once you understand that what you're trying to do is (1) define a language [basic arithmetic and some simple functions] and (2) write an interpreter for that language, you can then decide if you're ready to undertake that level of effort.

I'm not going to provide you any additional direction at this point, because I don't have the extra time right now to start writing my own arithmetic interpreter! Best wishes!

ok,i recently found out how to do it. I just have two problems, I cant get C++ to be able to detect random variables. My other problem is when i enter an equation with 2 operators, the program freaks out and exits. (x + 5 - 2 = 34)

#include<iostream>
#include<cstdio>
#include<cmath>
#include<ctime>
using namespace std;
int main (char argc)
{
    
    for(;;)
    {
           
    cout << "Variable equation solver version 1.0." << endl;
    cout << "Planned for next update: you can input more than just one operator." << endl;
    cout << "Limitations on this version: you can only use one operator, no ( and ), only can have the program solve one variable." << endl;
    
    char operators, operators2;
    double n1, n2, n3, ans;
    
    cin >> n1;
    
    cin >> operators;
    
    cin >> n2;
    
    cin >> operators2;
    
    cin >> n3;

    cout << "Which number do you want for the variable? (first number is #1)" << endl;
    
    float v1;
    cin >> v1;
    
    
    for(;;)
    {
    
    if(v1 == 1)
    {
          
          if(operators == '+')
          {
                       ans = n3 - n2;
          }
          
          if(operators == '-')
          {
                       ans = n3 + n2;
          }
          
          if(operators == '/')
          {
                       ans = n3 * n2;
          }
          
          if(operators == '*')
          {
                       ans = n3 / n2;
          }
          
          cout << "the variable equals "<<ans<< endl;
          break;
    }
    
    if(v1 == 2)
    {
          if(operators == '+')
          {
                       ans = n3 - n1;
          }
          
          if(operators == '-')
          {
                       ans = n3 + n1;
          }
          
          if(operators == '/')
          {
                       ans = n3 * n1;
          }
          
          if(operators == '*')
          {
                       ans = n3 / n1;
          }
          cout << "the variable equals "<<ans<< endl;
          break;
          }
          
          if(v1 == 3)
          {
                if(operators == '+')
          {
                       ans = n1 + n2;
          }
          
          if(operators == '-')
          {
                       ans = n1 - n2;
          }
          
          if(operators == '/')
          {
                       ans = n1 / n2;
          }
          
          if(operators == '*')
          {
                       ans = n1 * n2;
          }
          cout << "the variable equals "<<ans<< endl;
          break;
          }
          
          }
          system("pause");
          system("cls");
    }
}

Edited 5 Years Ago by thecoolman5: n/a

Consider using arrays, to reduce the amount of repeated and nearly identical code:

double n[3], ans;
char operators[2];
int n_index;

cout << "equation: ";
cin >> n[0] >> operators[0] >> n[1] >> operators[1] >> n[2];

cout << "which number do you want to replace with a variable (starting with 1)? "
cin >> v_index;
v_index -= 1;  // index starts from zero

int index_1, index_2;
bool reverse_operators = False;

// assuming the second operator is the '='
if (v_index == 0) {
    index_1 = 2;
    index_2 = 1;
    reverse_operators = True;
}
else if (v_index == 1) {
    index_1 = 2;
    index_2 = 0;
    reverse_operators = True;
}
else {
    index_1 = 0;
    index_2 = 1;
}

if (operators[0] == '+') {
    if (reverse_operators)
        ans = n[index_1] - n[index_2];
    else
        ans = n[index_1] + n[index_2];
}
else if (...

Now to be more generally useful, you'd like to be able to detect variables (and eventually function names like 'sqrt'), and it would be good to be able to find '=' signs as well.

The std::string class is a good place to start, and cstdlib functions skip over whitespace, so you can just read in a whole line once, and then see what you have.

// TODO: make tokens[] a dynamically growable array
std:string line;

cout << "Enter equation: ";
getline(cin, line);

const char *line_chars = line.c_str();
const char *line_ptr = line_chars;

// assuming the only options are numbers, variables, and the operators +-*/=
// and that they are in a sensible order like x + 3 = 5

struct operand {
    bool is_variable;
    double value;
    std::string variable;
};
typedef struct operand Operand;

Operand operands[MAX_OPERANDS];
char operators[MAX_OPERANDS];
int num_operands = 0;

while (line_ptr - line_chars < line.length()) {
    const char *next_ptr = line_ptr;
    double val = strtod(line_ptr, &next_ptr);
    if (next_ptr == line_ptr) {
        // failed to read a valid double, must be a variable
        size_t space_len = strcspn(line_ptr, " ");
        line_ptr += space_len;  // skip spaces
        size_t var_len = strcspn(line_ptr, "+-*/=");
        operands[num_operands].is_variable = True;
        operands[num_operands].variable = std::string(line_ptr, var_len);
    }
    else {
        operands[num_operands].is_variable = False;
        operands[num_operands].value = value;
    }
    // since an operand is always followed by an operator (so far), we can just
    // re-use num_operands
    // consolidating space-skipping lines used above...
    line_ptr += strcspn(line_ptr, " ");
    if (*line_ptr == '\0') {
        // no more operands, must be at end of equation
        num_operands++;
        break;
    }
    operator[num_operands] = *line_ptr;
    line_ptr++;

    num_operands++;
}

Sadly, I don't have a valid C++ compiler on this machine, so I'll have to let you try it out and fix any errors. I regularly use www.cplusplus.com as a reference source, I think any unfamiliar functions above? ... I probably just looked up there. :)

Now try to replace the evaluation loop I provided first, with one that handles Operand structs instead of doubles-and-an-index-for-which-one-is-the-variable. Let me know how it goes!

as i said before, i am a early beginner in C++. That second code snippet you posted had 9 errors. `MAX_OPERANDS' undeclared (first use this function), invalid conversion from `const char**' to `char**', initializing argument 2 of `double strtod(const char*, char**)',`operands' undeclared (first use this function), `True' undeclared (first use this function), `False' undeclared (first use this function), `value' undeclared (first use this function), expected identifier before '[' token

also, you can download DEV-C++ for free. Just search it on google. its easy to use and the download is legal.

oh one more thing, i almost got it to work by declaring n1, n2, n3, ans as a char. and if n1 = 'x' then i redeclare n2, n3, ans as floats. That works but the answer comes out as an extremely low number. why would redeclaring a char to a float decrease the number really low?

Hey thecoolman5,
I have cygwin and mingw32 installed on the machine, but unfortunately it's a 64-bit Win7 box, and for whatever reason, the mingw version of g++ is really unhappy in that environment. I've been meaning to fix it forever, but my actual "work" is purely in Python now, so it's not a job requirement to get to it. ;)

MAX_OPERANDS was for you to define, you clearly know how (?) from your previous code. True and False are the Python versions, sorry, C++ uses true and false (lower case) ... the dangers of working in multiple languages! You can remove the "const" from next_ptr at line 25. Since I'm not changing the string, I think declaring it const is the "correct" thing to do, but the declaration of strtod doesn't want it. It might also depend on whether you're hitting the strtod() from stdlib.h (which is C, and predates "const"-ness) or std::strtod() from cstdlib. And probably more. Anyway, my point was to illustrate how you could work with more complex structures and arrays to simplify your code and make it more readable and maintainable.

Anyway, you don't want to "redeclare" your variables (presumably within an enclosing block, otherwise you'd get a compiler error). What you're actually doing in that case is creating a new variable (with its own memory) with the same name as the previously existing one(s), thus "masking" the previous ones (and making them difficult or impossible to access within that block). The extremely low values are probably a result of uninitialized memory. Instead you want to "convert" those values. And I assume you're declaring them as char arrays? Otherwise you can only get single-digit numbers and variables.... You then use a function like atol() to convert a string to a new integer variable, or strtod() to convert to a new double (these are pre-built functions that understand how to handle each of the characters in a string, e.g., "-12345" [which is 7 characters, including the terminating '\0'], and convert it into a "long int" (4 bytes on a 32-bit machine, possibly more on a 64-bit) or "double" (almost always an 8-byte value). There has been at least one sample implementation of something like atol() posted in either this forum or the C forum, if you want to take a look.

ok, i tried and tried but i fixed the code that had nine errors. it ran ok but after i entered my equation, it crashed. I did what you said on using atol() but i cant get that to work either. i wonder if there is a way to have C++ figure out the equation with everything declared as a char. I have had it say what n2 equaled after i entered it and it came out as what i put.

Dev-C++ is no longer supported, last I checked. A better IDE will probably compile it.

What do you mean?

Oh wow, I think this forum has a bug! I definitely posted that somewhere else. I've had other forums do this to me too... Hmm.. Maybe it was user error then, oh well. Disregard that.

Well, despite my best efforts, I can't yet read minds. Post up the code you have at this point, and I'll at least try to figure out why it's crashing. And we'll see where to go next.

i actually forgot to save the program and now im stuck with the program that has nine errors. i did as much as i could but i keep getting these 5 errors: 40 invalid conversion from `const char**' to `char**' 40 initializing argument 2 of `double strtod(const char*, char**)' 43 invalid conversion from `const char' to `const char*' 43 initializing argument 1 of `size_t strcspn(const char*, const char*)' 62 expected identifier before '[' token

just recently, since i couldnt get atol(); to work, i actually went and changed atol(const char*); to atol(char); in the stdlib.h file. the program ran but after i entered my equation, the program crashed.

just recently, since i couldnt get atol(); to work, i actually went and changed atol(const char*); to atol(char); in the stdlib.h file. the program ran but after i entered my equation, the program crashed.

How did you change the atol() code in the run-time library to match your change? Or did you only change the declaration in the header? Think about it...

I recently couldn't get around the lake easily to get to the east side of town, so I changed the city map to have a bridge. But I almost drowned when I took the bridge. What went wrong... :icon_rolleyes:

I changed the declaration of the header. I changed it back after my program crashed.

As I suggested previously, feel free to remove the "const" wherever you have "const char *" in your code ... it adds extra checking for "correctness", but isn't strictly necessary, and it's wreaking havoc with your use of the C functions from stdlib.h.

As WaltP pointed out, you can't (usefully) change the declarations in the standard headers: those tell you what the default libraries are expecting to receive so that you can compile against them -- think of them as read-only, and provide what they indicate. In this case, atol() doesn't take single characters, it takes C-style strings (arrays of characters with terminating '\0' characters. A quick-and-dirty approach is

char n1_str[2];
n1_str[0] = n1;
n1_str[1] = '\0';
int n1_val = atol(n1_str);

but as I said before, using single characters for n1, n2, n3 means you can't use multi-digit numbers like 10 or 22.

I'm going to go way out on a limb here, and suggest that if you can't fix errors that say a given function expected a "char **" instead of a "const char **" and/or don't even understand what those errors mean, then you're in way over your head here. In answer to your earlier question to the effect of "why can't C++ just handle the strings" ... it can -- it's a process called parsing, and it's what we're working on here. It's a pain in the ass, and the code I've provided to date probably isn't 100% correct yet, but since we can't even get it to run, we're not in a position to worry about what mistakes it might make.

I very strongly recommend that you set this project aside and work your way through some introductory tutorial material designed to get you comfortable with the essentials of programming in C++, before you try to take on challenging problems like implementing your own implicit equation solver. Either way, good luck, and feel free to get back to us with specific questions!

Ok. If I can't get the program to work, I'm propably going to give up on it until I learn the rest of the c++ language. I appreciate all the help you have given me.

one more thing. i took your last code snippet and used it in my program and it worked. But, you were right on i can only use 1 digit numbers. How can i use multi-digit numbers?

An array of characters, when interpreted as a string, is often called a C string or a C-style string.

It has the special property that most code expects it to be NULL terminated, meaning the last character in the array (or the end of the string) has a NULL value.

take this for example:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
char buffer[256] = {1};//<-- the array contains ones.
strcpy(buffer,"Hello, C string.");//<-- this function automatically appends a NULL

//Now printing the string characters interpreted as integers will show this.
for(int i = 0; i < 256; i++)
cout << (int)buffer[i] << ' ';//<-- casted to an integer.
}
This question has already been answered. Start a new discussion instead.