-4

Giving input as:

Input:
    3
    1 2 3 
    4 5 6 7
    8 9 10 11 12
Expected Output:
    1 2 3
    4 5 6 7
    8 9 10 11 12
But it is giving the Output-
 1 2 3
 4 5 6 7
Why it is not giving the last line ? Is there any mistake in my code?
#include <iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;

int main() {
int t;
cin>>t;
while(t--)
{   string str;
    getline(cin,str,'\n');
    cout<<str<<endl;
}
return 0;
}
vikas2cc
  • 33
  • 9
  • `string.h` sure?? – user0042 Aug 24 '17 at 17:34
  • Why do people feel the need to punish someone with downvotes for asking a question just because it's a duplicate? It's not at all obvious how you would search for the answer to this. I thought the question was adequately asked. – Mark Ransom Aug 24 '17 at 17:40
  • @Mark Since when are DVs for _"punishing"_ a user? They are about usefulness of content. As a user with such high rep you should well know that. – user0042 Aug 24 '17 at 17:42
  • @user0042 since downvotes affect your reputation, which affects the ability you have to use the site, it is indeed punishment whether that's intended or not. – Mark Ransom Aug 24 '17 at 17:49
  • @Mark Well, we require (force) users to do some research before asking. You're right insofar that the duplicate isn't obvious, though not impossible to find a lot of hints about that specific behavior of formatted text extraction and `std::getline()`. If at all we're punishing _laziness_ in research to keep Stack Overflow clean and useful. Answering such questions only slow down the process of roombaing such frequent questions. So please don't if you know better. – user0042 Aug 24 '17 at 17:57
  • 1
    @user0042 i am new user to stackoveflow... i am getting the point what u are saying .....i will do more research on any quesiton before submitting next time.. – vikas2cc Aug 24 '17 at 18:01
  • _@vikas2cc_ @Mark Mission of voting system accomplished. – user0042 Aug 24 '17 at 18:02
  • @user0042 I'm not fond of the roomba either, sometimes it's OK to have multiple questions so that a search has a better chance of finding a solution. – Mark Ransom Aug 24 '17 at 18:22

1 Answers1

-1

It's because cin>>t doesn't read the end-of-line. The first time you call getline you're getting an empty string.

I can think of a couple of ways of getting around this offhand. First is to skip over the whitespace at the end of the first number, since a newline counts as whitespace. Unfortunately this will also skip whitespace at the beginning of the next line.

cin >> t >> std::ws;

The other way is to use getline to skip past the end of the line and ignore the string you get back.

cin >> t;
getline(cin, str, '\n');
Mark Ransom
  • 271,357
  • 39
  • 345
  • 578