Day 1 - Data Types

HackerRank's 30 Days of Code

·

3 min read

Takeaways of the day:

  • fixed and setprecision()

  • getline(cin, stringname)

  • cin.ignore()

The challenge:

I attempted HackerRank's challenge today feeling pretty confident about this challenge. Afterall, it did look simple enough. Declaring variables, I can do that. Getting input? No problem. (or so I thought) Printing the results out? How hard could that be?

I was dearly mistaken, however, when I confidently sent my code for the test run and got this back instead.

Well, at least I got one right...

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    int i = 4;
    double d = 4.0;
    string s = "HackerRank ";

    int x = 0;
    double y = 0.0;
    string z = "";

    cin >> x;
    cin >> y;
    cin >> z;

    cout << i + x << endl;
    cout << d + y << endl;
    cout << s << z << endl;

    return 0;
}

Upon closer inspection, I quickly realised that I forgot to #include <string> and I obviously needed to do something about the decimal points for the double. Hence, i quickly googled regarding decimal points on Google and came across the setprecision() function.

Furthermore, the use of fixed was necessary to override the pre-existing output format in order to follow the desired display as indicated through setprecision() .

With that, I changed my code into something like this.

cout << fixed << setprecision(1) << d + y << endl;

However, I still couldn't figure out why my string wasn't getting read, until I realised that up to this point, I have never tried to cin >> string. A quick search on the internet told me that brute forcing a cin >> string wasn't going to work, and what I needed was getline(cin, stringname) instead.

However, to my horror, the seemed to be further away from the answer than ever.

My previous code, at the very least, still displayed one more word than this new code! With so many questions in my head, I turned to, once again, my most loyal companion in this journey.

I found out that it was due to the fact that the previous cin used to get an input for the double has resulted in an input buffer. By using getline() immediately resulted in the "\n" getting read instead of the actual input. As such, the solution was to use cin.ignore() in order to ignore that input buffer.

After all these, I finally arrived at my code that passed me with flying colours. Yay!

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

int main() {
    int i = 4;
    double d = 4.0;
    string s = "HackerRank ";

    int x = 0;
    double y = 0.0;
    string z = "";

    cin >> x;
    cin >> y;
    cin.ignore();
    getline(cin, z);

    cout << i + x << endl;
    cout << fixed << setprecision(1) << d + y << endl;
    cout << s << z << endl;

return 0;
}

See you in the next post!