CodingKnight's blog

By CodingKnight, 2 years ago, In English

Hello Codeforces,

It is well-known that C++ Input/output manipulators such as fixed, setprecision, endl, etc. are helper functions that serve as user-friendly control commands to input/output streams.

An input-stream command that is necessary but not common in competitive programming is to discard all characters until and including the new-line character. An example for this issue is the following HackerEarth problem. Although the problem is very easy, its data-input invovles a trick that the input string in each line can include a space character as a part of the string.

Using the function call std::getline(cin,s) to read the line which includes space characters right after reading the number of test cases using the input command cin >> t causes the first call of std::getline(cin,s) to read an empty string, as the new-line character at the end of the first line which contains the number of test cases would have not been read yet.

It is possible to use an extra call to std::getline(cin,s) to solve this issue, but a more elegant solution is to declare and use a simple C++ input-stream manipulator whose purpose is to disard the new-line character using a call to the standard function std::istream::ignore.

The followng is the one-line code of the skip_endl input-stream manipulator.

#include <bits/stdc++.h>
using namespace std;

inline istream& skip_endl(istream &is) { return is.ignore(numeric_limits<streamsize>::max(),'\n'); }

And the following is a simple example for using it.

inline string solve(const string &s) {
    string t;
    // code to convert each character in string (s) into its equivalent character(s) 
    // in string (t) should be written here
    return t; }

int main() {
    int t; string s; 
    ios_base::sync_with_stdio(0), cin.tie(0), cin >> t >> skip_endl; 
    while (t--) 
        getline(cin,s), cout << solve(s) << '\n'; }

Your constructive comments and remarks are welcome.

Stay safe, and keep the good work going.

P.S. HackerRank default C++14 code in practice problems often includes the explicit command cin.ignore(numeric_limits<streamsize>::max(),'\n') for the same purpose.

  • Vote: I like it
  • +26
  • Vote: I do not like it