Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getline()

Status
Not open for further replies.

piofenton

Instructor
Jul 12, 2002
33
IE
Hi,
If I want to read a line of unspecified length and discard it, which derivative of getline() should I use?
If I use getline(str, 80, "/n") I keep the first 80 chars but also I need to know that I won't be reading more than 80 chars. Is there any way around this?

Thanks
P.
 
Well, in most cases you can just pick some really big value that probably won't ever be exceeded. Computers have a lot of memory; don't worry about that, you can use a buffer of 1000 or more and you'll probably be safe. If you would have something absolutely huge though and you want to be sure, you could just do a loop and use get() instead of getline() like this:

char ch = 'a';
while(ch != '\n')
cin.get(ch);

Although it would probably be better to use read() instead to get some number of chars in a buffer and then look through that for \n.
 
Code:
#include <limits>
std::numeric_limits<streamsize>::max();
is the maximum stream size. That may help.

Your shell probably also sets a maximum line length that can be typed. It's usually perfectly reasonable to say your application will not handle lines longer than the above constant.
 
If you just want to discard it, you can use ignore:
Code:
std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');

Also, the getline that works with the C++ standard string class doesn't require a buffer size, so technically that would be easier than hoping that your buffer is big enough. Of course, ignore is better if you are just going to ignore the value completely.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top