Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take a specified number of lines as input?

Tags:

c++

string

cin>>string takes input until space or new line. But getline(cin,string) takes input until new line. Again, getline(cin,string,'c') takes input until 'c'. Is there any way to ignore a few '\n' character and take a specified number of lines as input?

I tried the code below but it didn't work

int main()
{
   string a;
   for(int i=0;i<4;i++)
   {
       getline(cin,a);//take string input 
   }
   cout<<a;
}

here for the following input

 ksafj kfaskjf(\n)1st
 uuiiuo akjfksad(\n)2nd
 ksafj kasfj(\n)3rd
 asdfed kkkl(\n) when the 4th enter comes input terminate

string a only holds "asdfed kkkl". I want it to hold all the characters, including the end-of-lines (\n).

like image 505
Sofi Ullah Saikat Avatar asked May 04 '16 17:05

Sofi Ullah Saikat


1 Answers

Do you want to get the first n lines?

std::string get_n_lines(std::istream& input, const std::size_t n)
{
  std::ostringstream result;
  std::string line;
  std::size_t i = 0;

  while (std::getline(input, line) && i < n)
  {
    result << line << '\n';
    ++i
  }

  return result.str();
}

std::string first_4_lines = get_n_lines(std::cin, 4);
like image 183
erenon Avatar answered Sep 28 '22 17:09

erenon