Does getline() not extract the delimiter?

3165 views c++
3

So I was taking input some integers and then taking input some sentences.

This code works fine:

#include<bits/stdc++.h>
using namespace std;
main(){
    int c,b,n,i;string s;
    cin>>n>>b>>c;
    cin>>ws;
    for(i=0;i<n;i++){
        cin>>ws;
        getline(cin,s,'\n');
        cout<<s; 
     }
    }

However, when I try to omit the cin>>ws inside the forloop, it doesn't work properly, eg this code segment,

#include<bits/stdc++.h>
using namespace std;
main(){
    int c,b,n,i;string s;
    cin>>n>>b>>c;
    cin>>ws;
    for(i=0;i<n;i++){
            getline(cin,s,'\n');
            cout<<s;
    }
}

Why is that? cin>>ws extracts all whitespace from the input but isn't getline() doing that too? So why does it just take one input and exit without printing anything when I omit cin>>ws in the forloop?

answered question

3 Answers

6

std::getline() only extracts the first "newline" character (by default '\n'). It does not extract whitespace in general or multiple newline characters.

As an aside: always check whether input works after trying to read a value.

posted this
5

The getline() function will stop taking input upon finding EITHER the delimiter or a newline '\n'.

By calling getline() inside a loop while using '\n' as the delimimter, you are forcing the getline() to be called twice to get past the end of the line, hence the problem with your code.

Change the line to

getline(cin,s);

posted this
7

Cin doesnt extracts all white spaces, cin just extracts the word untill the first white space. It is like having a getline with a space delimiter(not quite but close to).

Getline takes the whole line and has the default '\n' delimiter like mentioned above.

Ex: string a = "Stack Overflow is awesome";

cin will give you stack and getline will give you everythin at that line

posted this

Have an answer?

JD

Please login first before posting an answer.