HackerRank: Day 1: Data Types in C++
They are asking me to declare 3 variables, one for integer, one for double and one for string. Then read 3 lines of input from stdin. I have posted up my solution but it is not working. I don't know why my variable for string is not reading from the stdin. When I try it in the VSCODE, it is working. Can you tell me what am I doing wrong?
Here is the problem
Sample input:
12
4.0
is the best place to learn and practice coding!
Sample output:
16
8.0
HackerRank is the best place to learn and practice coding!
This is the code I use to check in my VSCODE. This works! But it doesn't work in HackerRank website.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
// Declare second integer, double, and String variables.int x;
int x;
double y;
string str;
// Read and save an integer, double, and String to your variables.
cin >> x;
cin >> y;
getline(cin, str);
// Note: If you have trouble reading the entire string, please go back and review the Tutorial closely.
// Print the sum of both integer variables on a new line.
cout << x + i << endl;
// Print the sum of the double variables on a new line.
cout << y + d << endl;
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
cout << s + str << endl;
return 0;
}
After reading input using std::cin, there will be an extra line left which is read by the getline() everytime.
Try using std::cin.ignore() before reading the string.
It will ignore the extra line.
std::cin>>x;
std::cin.ignore();
std::getline(std::cin,str);