yoda is hosted by Hepforge, IPPP Durham
YODA - Yet more Objects for Data Analysis 2.0.2
getline.h
Go to the documentation of this file.
1// -*- C++ -*-
2//
3// This file is part of YODA -- Yet more Objects for Data Analysis
4// Copyright (C) 2008-2024 The YODA collaboration (see AUTHORS for details)
5//
6#ifndef YODA_GETLINE_H
7#define YODA_GETLINE_H
8
9#include <iostream>
10#include <string>
11
12namespace YODA {
13 namespace Utils {
14
15
16 // Portable version of getline taken from
17 // http://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf
18 inline std::istream& getline(std::istream& is, std::string& t) {
19 t.clear();
20
21 // The characters in the stream are read one-by-one using a std::streambuf.
22 // That is faster than reading them one-by-one using the std::istream.
23 // Code that uses streambuf this way must be guarded by a sentry object.
24 // The sentry object performs various tasks,
25 // such as thread synchronization and updating the stream state.
26 std::istream::sentry se(is, true);
27 std::streambuf* sb = is.rdbuf();
28
29 for (;;) {
30 int c = sb->sbumpc();
31 switch (c) {
32 case '\n':
33 return is;
34 case '\r':
35 if (sb->sgetc() == '\n')
36 sb->sbumpc();
37 return is;
38 case EOF:
39 // Also handle the case when the last line has no line ending
40 if (t.empty())
41 is.setstate(std::ios::eofbit);
42 return is;
43 default:
44 t += (char)c;
45 }
46 }
47 }
48
49
50 }
51}
52
53#endif
Anonymous namespace to limit visibility.