0

Why doesn't the getline function takes input here ?

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

int main() {
    unsigned n {}, m {};
    cin >> n >> m;

    string set;
    getline(cin, set);
    cout<<set<<endl;
    return 0;
}

INPUT PROVIDED:

1 5
Hello World

OUPUT DISPLAYED:


Rishi K.
  • 111
  • 1
  • 8
  • 3
    Does this answer your question? [Using getline(cin, s) after cin](https://stackoverflow.com/questions/5739937/using-getlinecin-s-after-cin) – Rhathin Jan 09 '20 at 10:59

1 Answers1

1

std::getline(istream&,std::string&) doesn't work the same way cin>>var works. When you use cin>>var the right input is absorbed to the var correctly and if there is a space before it it is ignored but std::getline doesn't ignore the space, so we used std::cin.ignore() to ignore the \n. If you don't ignore it, the string will encouter it and then won't absorb your line because std::getline() stops on encountering a \n.

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

    int main() {
        unsigned n {}, m {};
        cin >> n >> m;

        string set;
        cin.ignore();
        getline(cin, set);
        cout<<set<<endl;
        return 0;
    }
asmmo
  • 6,922
  • 1
  • 11
  • 25