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??
How to skip lines while using cin <<
Moderator: Board moderators
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
-
- New poster
- Posts: 27
- Joined: Wed Apr 17, 2002 7:54 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.
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.
-
- New poster
- Posts: 14
- Joined: Tue Oct 19, 2004 2:01 am
The correct answer
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]
[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, ......
int main()
{
int n;
cin.ignore(4); // '1' + '\n' + '2' + '\n' = 4 chars
cin>>n;
cout<<n<<endl; // output: 3
}
{
int n;
cin.ignore(4); // '1' + '\n' + '2' + '\n' = 4 chars
cin>>n;
cout<<n<<endl; // output: 3
}