Challenge - 5 Problems
Cin Input Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
What is the output of this code reading two integers?
Consider the following C++ code that reads two integers from the user and prints their sum. What will be the output if the user inputs
3 7?C++
#include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; cout << a + b << endl; return 0; }
Attempts:
2 left
๐ก Hint
Remember that
cin reads values separated by spaces and stores them in variables.โ Incorrect
The code reads two integers 3 and 7, then outputs their sum, which is 10.
โ Predict Output
intermediate2:00remaining
What happens if input is a word instead of a number?
What will be the output or behavior of this code if the user inputs the word
hello instead of a number?C++
#include <iostream> using namespace std; int main() { int x; cin >> x; cout << x << endl; return 0; }
Attempts:
2 left
๐ก Hint
Think about what happens when
cin tries to read an integer but gets a non-numeric string.โ Incorrect
When
cin tries to read an integer but the input is not a number, it sets a fail state and does not assign a value to x. The variable x remains uninitialized or zero if default initialized.๐ง Debug
advanced2:00remaining
Why does this code not read the full line after reading an integer?
This code reads an integer and then tries to read a full line of text. Why does the second input read an empty string?
C++
#include <iostream> #include <string> using namespace std; int main() { int n; string line; cin >> n; getline(cin, line); cout << "Number: " << n << endl; cout << "Line: " << line << endl; return 0; }
Attempts:
2 left
๐ก Hint
Think about what remains in the input buffer after reading with
cin >>.โ Incorrect
After reading the integer, the newline character remains in the input buffer. The
getline reads this leftover newline as an empty line.๐ Syntax
advanced2:00remaining
Which option correctly reads three integers using cin?
Which of the following code snippets correctly reads three integers a, b, c from the user using
cin?Attempts:
2 left
๐ก Hint
Remember the operator used with
cin to read multiple values.โ Incorrect
The correct syntax to read multiple variables with
cin is chaining the extraction operator >> like cin >> a >> b >> c;.๐ Application
expert2:00remaining
What is the value of x after this input sequence?
Given the following code, what will be the value of
x after the user inputs 42 hello 100?C++
#include <iostream> #include <string> using namespace std; int main() { int x; string s; cin >> x >> s >> x; cout << x << endl; return 0; }
Attempts:
2 left
๐ก Hint
The input reads in order: integer, string, integer. The last integer overwrites x.
โ Incorrect
The first
cin >> x reads 42 into x. Then cin >> s reads "hello". Finally, cin >> x reads 100, overwriting the previous value of x. So x is 100.