int *num = new int[0];
this actually worked for me previously so I used it again hehe. But yes, I get your point. From now on, will be allocating NULL to my pointer. thank you!
Change in size, I think it will do good. My code below will tell why exactly I changed it in that way.
Yes, resize will lose the data. I forgot to add one more line in it, thank you.
No, its actually a little different. This is what's happening here, (from the start)
0 * 10 = 0
0 + 1 = 1
1 * 10 = 10
10 + 0 = 10
10 * 10 = 100
100 + 0 = 100
So, that's how it is supposed to give me 100... I think it should work good.
I am allowed to use tools. Problem here is, I don't know much of tools. We are still in quite beginning of C++. We have studied Classes and Struct etc but haven't yet studied Vector so can't really use them. But yes, I can use substr and then use stoi to convert string into number. I didn't realize that.
Thanks for this suggestion... And following this, I tried to make a program, but again, it's giving a run time error :/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
string a = "5+10+100";
int f = 0, l = 0, size = 0;
int *num = NULL, *temp;
string t;
for (int i = 0; i < a.length(); i++)
{
if (a[i] == '+' || a[i] == '-' || a[i+1] == '\0')
{
if (a[i+1] == '\0')
t = a.substr(f, i);
else
t = a.substr(f, i-1);
f = i + 1;
temp = new int[size + 1];
for (int i = 0; i < size; i++)
temp[i] = num[i];
delete[]num;
num = temp;
num[size] = stoi(t);
size++;
}
}
for (int i = 0; i < size; i++)
cout << num[i] << endl;
cout << endl;
system("pause");
return 0;
}
|
The logic here is this that there is first index number which will be stored in variable int... And the last index number will be whatever stored in "i".
So, whenever "+" comes, I will take a substring from "f" to "i-1" (the character before "+"), i.e. "5" in first case.
However, there is still an error being generated on num[size] = stoi(t) and I have no idea why is it so :/
(You can see how I am using size here.. Basically it stays zero so that I can add a value into that index i.e. 0th index for first case. And then I make an addition in it.)