Page 1 of 1

How to skip lines while using cin <<

Posted: Wed Dec 10, 2003 2:13 pm
by dapumptu
How to skip lines while using cin << ??

for example:

1
2
3

i want to read 3 and skip 1 and 2.

How to do this??

Posted: Thu Dec 11, 2003 1:17 pm
by Krzysztof Duleba
[cpp]string tmp;
for(int i=0;i< ...; ++i)getline(cin,tmp);
[/cpp]
It will skip a given number of lines.

Posted: Sat Dec 27, 2003 9:26 pm
by Juergen Werner
... but be careful if you want to skip lines after using cin << ..., because there is still a newline left.

It might be a good idea - whenever there is a need to read a whole line - to read all lines in whole and then getting the values with istringstream or sscanf, then there is no need to worry about newlines that might or might not have been read.

Posted: Sat May 29, 2004 1:57 pm
by Examiner
I'll simply write:
[cpp]int n, dummy;
cin >> dummy >> dummy >> n;
[/cpp]

Posted: Tue Oct 12, 2004 7:35 pm
by TISARKER
void skipline(int n)
{
int i,temp;
for(i=0;i<n;i++)cin>>temp;
}

This function skips line.Paramiter n is the number of skip lines.
Thanks :o

Posted: Tue Oct 26, 2004 4:01 pm
by eg_frx
TISARKER wrote:void skipline(int n)
{
int i,temp;
for(i=0;i<n;i++)cin>>temp;
}

This function skips line.Paramiter n is the number of skip lines.
Thanks :o
It only works for single-integer lines. If the line has an alphabetic word, or more than one values, this will fail to do what you intended.

The correct answer

Posted: Tue Nov 02, 2004 5:22 pm
by Michael Goldshteyn
The right way, use:

[cpp]
#include <iostream>
#include <string>

const size_t num_lines_to_skip=2;
std::string s;

for (size_t i=0;i<num_lines_to_skip;++i)
std::getline(cin,s);
[/cpp]

Ummmmmm, ......

Posted: Fri Sep 16, 2005 9:47 am
by rmotome
int main()
{
int n;
cin.ignore(4); // '1' + '\n' + '2' + '\n' = 4 chars
cin>>n;
cout<<n<<endl; // output: 3
}