I take equation from a user (ex: 1X1+2X2=24 ) whatever the number of variables , i am toking it to 1X1 ,2X2 by +, - or = and then put them in array of char and each toking by x or X, and put it on another array ,but some garbage comes
#include<iostream>
#include <stdio.h>
#include <string.h>
#include<string>
#include <algorithm>
#include<vector>
using namespace std;
int main()
{
string a;
cout<<"Enter Equation: "<<endl;
cin>>a; //string of the equation
int num= a.size();
char str[num]; //view it as array of char
for (int k=0;k<num;k++)
{
str[k]=a[k];
cout<<str[k];
}
int i=0;
char *pch;
int count = 0;
for (int i = 0; i < a.size(); i++)
{
//counting + , - and = to see how many element i need in array
if (a[i] == '+'||a[i] == '-'||a[i] == '=')
count++;
}
char *array[count];
cout<<"\nSplitting string into tokens: "<<a;
pch = strtok (str,"= + -");
while (pch != NULL)
{
array[i++]=pch;
pch = strtok (NULL, "= + -");
}
// printing every variable
for(i=0;i<count+1;i++)
{
cout<<endl<<array[i];
}
char *pch_var;
char *array_var[2];
for(int j=0; j<count+1;j++)
{
cout<<"\nSplitting Variable into tokens: "<<array[j];
pch_var = strtok (array[j],"x X");
while (pch_var != NULL)
{
array_var[i++]=pch_var;
pch_var = strtok (NULL, "x X");
}
cout<<array_var[0]<<endl<<array_var[1];
}
return 0;
}
the out comes be like that
Enter Equation:
1X1+2X2=24 // from user
1X1+2X2=24 //here start my code function
Splitting string into tokens: 1X1+2X2=24
1X1
2X2
24{t{k║
Splitting Variable into tokens: 1X1P■m
]├ï Uï∞â∞SVWh
Splitting Variable into tokens: 2X2P■m
]├ï Uï∞â∞SVWh