How to skip lines while using cin <<

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
dapumptu
New poster
Posts: 5
Joined: Tue Nov 25, 2003 3:30 pm

How to skip lines while using cin <<

Post by dapumptu » Wed Dec 10, 2003 2:13 pm

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??

User avatar
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba » Thu Dec 11, 2003 1:17 pm

[cpp]string tmp;
for(int i=0;i< ...; ++i)getline(cin,tmp);
[/cpp]
It will skip a given number of lines.

Juergen Werner
New poster
Posts: 27
Joined: Wed Apr 17, 2002 7:54 pm

Post by Juergen Werner » Sat Dec 27, 2003 9:26 pm

... 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.

Examiner
New poster
Posts: 27
Joined: Thu Feb 19, 2004 1:19 pm

Post by Examiner » Sat May 29, 2004 1:57 pm

I'll simply write:
[cpp]int n, dummy;
cin >> dummy >> dummy >> n;
[/cpp]
What's in your hands, I think and hope, is intelligence: the ability to see the machine as more than when you were first led up to it, that you can make it more.
Alan J. Perlis

TISARKER
Learning poster
Posts: 88
Joined: Tue Oct 12, 2004 6:45 pm
Location: Bangladesh
Contact:

Post by TISARKER » Tue Oct 12, 2004 7:35 pm

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
Mr. Arithmetic logic Unit

eg_frx
New poster
Posts: 21
Joined: Sat Oct 02, 2004 2:17 pm

Post by eg_frx » Tue Oct 26, 2004 4:01 pm

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.

Michael Goldshteyn
New poster
Posts: 14
Joined: Tue Oct 19, 2004 2:01 am

The correct answer

Post by Michael Goldshteyn » Tue Nov 02, 2004 5:22 pm

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]

rmotome
New poster
Posts: 14
Joined: Mon Jan 10, 2005 12:20 pm
Location: Kitchener, Ontario, Canada

Ummmmmm, ......

Post by rmotome » Fri Sep 16, 2005 9:47 am

int main()
{
int n;
cin.ignore(4); // '1' + '\n' + '2' + '\n' = 4 chars
cin>>n;
cout<<n<<endl; // output: 3
}

Post Reply

Return to “C++”