Variables


Hi, I was trying to do a small program in which you have to insert two numbers and the operation you want to do and it gives you the result. i got to a point where i created variables num1 num2 and num3 = num1 + num2
I thought it would use the numbers I give to him with cin to make num3 but instead it uses random numbers. I hope you can help me.
(P.S. don't mind italian text)
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

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

int main()

{
    int num1;
    int num2;
    int num3 = num1 + num2;
    char operazione[0];

    cout << "Inserisci primo numero: ";
    cin >> num1;
    
    cout << "Inserisci secondo numero: ";
    cin >> num2;
    
    cout << "Inserisci operazione: ";
    cin >> operazione;
    
    if (strcmp("addizione", operazione) == 0)
   {
       cout<< num3;
   }
    
    
}
1
2
3
    int num1;
    int num2;
    int num3 = num1 + num2; //garbage value 


this is where it's wrong, you don't initialize num1 and num2, so they are going to be garbage values at first, then num3 will remain a garbage value because you summed 2 garbage values.

to fix it, you have to input num1 and num2 before summing num3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    int num1;
    int num2;
    int num3;
    std::string operazione;

    std::cout << "Inserisci primo numero: ";
    std::cin >> num1;
    
    std::cout << "Inserisci secondo numero: ";
    std::cin >> num2;
    
    std::cout << "Inserisci operazione: ";
    std::cin >> operazione;
    

    if (operazione == "addizione")
   {
       num3=num1+num2;
       std::cout<< num3;
   }
Last edited on
Thanks, but, I don't know why, it's still giving me a random value
I'm doing this now:
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
#include <iostream>
#include <string>
using namespace std;

int main()

{
    int num1;
    int num2;
    int num3;
    char operazione[0];

    cout << "Inserisci primo numero: ";
    cin >> num1;
    
    cout << "Inserisci secondo numero: ";
    cin >> num2;
    
    cout << "Inserisci operazione: ";
    cin >> operazione;
    
    if (strcmp("addizione", operazione) == 0)
    {
       num3 = num1 + num2;
        cout<< num3 << endl;
   }
    
    
}
Use std::string instead of char array, like I did in the previous post. You are making a constant array of size 0, so only 1 char.
Thanks a lot Golden Lizard, now it's working!
Last edited on
Topic archived. No new replies allowed.