Using cin | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Using cin

Edit: Hi again, I figured it out!! Yay. If you'd like to know how to do it tho go to C++ Basic concepts and the lesson on working w variables. Hi I've been experimenting with cin bec I just learned it and am trying to figure it out. I wrote a code to input what variable a is equal to and after it worked adapted it to try and get what a + b is equal with b being a set number and a being whatever u input it to be. This is the code plz help if u can, I just started programing. Tx in advance. #include <iostream> using namespace std; int main() { int a; int b = 37; int sum = a + b; cout << "Please enter a number:\n"; cin >> a; cout << sum; return 0; }

5th Oct 2018, 3:24 AM
Avi Gluck
Avi Gluck - avatar
2 Answers
+ 6
You've stumbled upon one of the most common beginner errors. Worry not, you are one step closer to being proficient. :> You see, the execution of the program begins with the main function, and everything in there goes from top to bottom, in order. In this case, you declared a, b and directly assigned the sum of a and b to sum. This takes place before cin, so your input value was not used. Instead, whatever garbage value was stored in variable a, was added to sum instead. To fix this, take input before you assign to sum. int a; int b = 37; cin >> a; int sum = a + b;
5th Oct 2018, 3:58 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
tysm Hatsy Rei
5th Oct 2018, 4:01 AM
Avi Gluck
Avi Gluck - avatar