Step through your code in order and you’ll see the problem:
int main () {
int a;
int b;
string number1;
string number2;
number1 = a;
number2 = b;
int output;
output = a + b;
getline (cin, number1);
getline (cin, number2);
cout << output;
}
You define four variables, fiddle with two of them in a weird way, and then calculate output as a+b.
By this point you haven’t actually interacted with the user. You finish doing all that, and THEN you accept your two values (as strings) and output the previously-calculated value.
You never use the values you pull in from input, as you do that after doing anything else.
Maybe try this:
#include <iostream>
#include <string>
int main () {
std::string number1;
std::string number2;
std::getline (std::cin, number1);
std::getline (std::cin, number2);
int a = std::stol(number1);
int b = std::stol(number2);
int output = a + b;
std::cout << output << std::endl;
}
That is, define your strings and then get them from the user.
std::stol is “string to long”. It converts the strings to numbers.
The rest should make sense.
0
solved Why does this c++ program not function correctly?