Filipi Maciel - 1 year ago 81
C++ Question

# Conversion of string to stack-int-value, when is negative, results in strange value

I'm trying to convert my string of numbers in a stack, but I don't understand why when the number is negative, the first element is always

`-3`
.

``````void Soma::StrToInt(char str1[], char str2[]) {
for (int i = 0; str1[i] != '\0'; i++) {
if (str1[0] == '-') {              //if is negative
negative1 = true;
}
p1.push(str1[i] - '0');
cout << p1.top() << endl;//Always showing the first element == -3
}

for (int i = 0; str2[i] != '\0'; i++) {
if (str1[0] == '-') {
negative2 = true;
}
p2.push(str2[i] - '0');
}
}
``````

The full code is too big to post here, the problem is why this
`-3`
value appears, when my string is negative, like
`-500`
,
`-9514897654654`
or any negative number.

Minimal version:

``````int main() {
char str1[] = { '-','4','0','0' };
stack<int> p1;

for (int i = 0; str1[i] != '\0'; i++) {
p1.push(str1[i] - '0');
cout << p1.top() << endl;
p1.pop();
}
}
``````

The issue here is that `p1.push(str1[i] - '0');` is trying to subtract `'0'` from `'-'` if the string holds a negative number since you always start with `i = 0`. What you need to do is check if the string is negative or not before the loop and then depending on that check start at `0` or `1`. You could have something like

``````void Soma::StrToInt(char str1[], char str2[]){
int start = 0;
if(str1[0] == '-'){              //if is negative
negative1 = true;
start = 1;
}
for(int i=start; str1[i]!='\0'; i++)
//...
}
``````

Now if the string is negative you will skip the `'-'` in the string and just push the numbers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download