Chetanrns
Chetanrns

Reputation: 29

In c++ getline() is not reading all the letters of the string while accepting multiple strings one after the other

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t; //Number of test cases
    while(t--){
        cin.ignore();
        string s;
        getline(cin,s);
        cout<<s<<endl;
    }
    return 0;
}

Input:

2
AMbuj verma
Aaaa bBBB
Bm Chetan

Output:

AMbuj verma
aaa bBBB
m Chetan

The above program is not reading first character of the strings.

This is the output that I'm getting.

I have also used cin.ignore()

Upvotes: 0

Views: 1225

Answers (3)

user2736738
user2736738

Reputation: 30926

Actually yes the cin.ignore() consumes your characters. Now to add something in detail the input is basically stored in buffer (not in case of redirection). Now when you use getline it does this.

(1) istream& getline (istream& is, string& str, char delim);
(2) istream& getline (istream& is, string& str);<--you used this

Extracts characters from is and stores them into str [getline(cin.str)]until the delimitation character delim is found (or the newline character, '\n', for (2)).

The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).

So when basically that \n is consumed and discarded by getline itself. Now you use cin.ignore()

istream& ignore (streamsize n = 1, int delim = EOF); Extract and discard characters Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.

So you didn't specify anything-- so it discards one character that is available in buffer which is the first character. (But you thought there would be the \n which will be consumed but it was not there as it was discarded by getline().

That's how you get the output like this.

Upvotes: 0

Aditi Rawat
Aditi Rawat

Reputation: 784

What you need to do is bring the cin.ignore() outside of your while loop since every time your loop works, it takes the first letter of your string.

    cin>>t; //Number of test cases
    cin.ignore();
    while(t--){

        string s,a;
        getline(cin,s);
        cout<<s<<endl;
    }

Lastly why are you writing string s, a when there is no use of string a in your code.

Upvotes: 2

NathanOliver
NathanOliver

Reputation: 180720

You are calling cin.ignore(); in the loop so it will ignore one character in every iteration. Since you only use operator >> once you need to move the call to ignore out of the loop and have it just after the input.

cin>>t; //Number of test cases
cin.ignore(); // get rid of newline
while(t--){
    string s,a;
    getline(cin,s);
    cout<<s<<endl;
}

Upvotes: 1

Related Questions