473,756 Members | 6,250 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

std::istream_it erator to read whole lines?

I am writing a program to read in a file, do some processing, then write
it out to a different file. I really like the idiom I use for output:

// std::vector<std ::string> vec;
// std::ofstream out;
std::copy(vec.b egin(),
vec.end(),
std::ostream_it erator<std::str ing>(out, "\n"));

Is there a way to do the same thing for input that will read whole
lines? I tried the obvious thing:

// std::ifstream in;
std::copy(std:: istream_iterato r<std::string>( in),
std::istream_it erator<std::str ing>(),
std::back_inser ter(vec));

but it separates on whitespace so every word is a different element in
the vector. I would like it to do the same thing as

// std::string line;
while (std::getline(i n, line)) {
vec.push_back(l ine);
}
It's not a big deal or anything. I would just like the the two
operations to look consistent.

--
Marcus Kwok
Dec 1 '05 #1
2 7071
On 2005-12-01, Marcus Kwok <ri******@gehen nom.net> wrote:
I am writing a program to read in a file, do some processing,
then write it out to a different file. I really like the idiom
I use for output:

// std::vector<std ::string> vec;
// std::ofstream out;
std::copy(vec.b egin(),
vec.end(),
std::ostream_it erator<std::str ing>(out, "\n"));

Is there a way to do the same thing for input that will read
whole lines? I tried the obvious thing:

// std::ifstream in;
std::copy(std:: istream_iterato r<std::string>( in),
std::istream_it erator<std::str ing>(),
std::back_inser ter(vec));

but it separates on whitespace so every word is a different
element in the vector. I would like it to do the same thing as

// std::string line;
while (std::getline(i n, line)) {
vec.push_back(l ine);
}


Implement a line-based input iterator. It should be a snap.

You could implement a line type instead, with a suitable
operator>>, but I don't like the idea as much.

--
Neil Cerutti
Dec 1 '05 #2
Neil Cerutti <le*******@emai l.com> wrote:
On 2005-12-01, Marcus Kwok <ri******@gehen nom.net> wrote:
I am writing a program to read in a file, do some processing,
then write it out to a different file. I really like the idiom
I use for output:

// std::vector<std ::string> vec;
// std::ofstream out;
std::copy(vec.b egin(),
vec.end(),
std::ostream_it erator<std::str ing>(out, "\n"));

Is there a way to do the same thing for input that will read
whole lines? I tried the obvious thing:

// std::ifstream in;
std::copy(std:: istream_iterato r<std::string>( in),
std::istream_it erator<std::str ing>(),
std::back_inser ter(vec));

but it separates on whitespace so every word is a different
element in the vector. I would like it to do the same thing as

// std::string line;
while (std::getline(i n, line)) {
vec.push_back(l ine);
}


Implement a line-based input iterator. It should be a snap.


OK, my template technique is not too strong yet, so here is what I came
up with. Basically, I copied the implementation of istream_iterato r
from the STL that comes with VS .NET 2003 (I believe they still use
Dinkumware) but renamed some of the implementation items, and added a
specialization for std::string, so this may not be the simplest or most
elegant way. If anyone knows a simpler way to specialize
istream_iterato r for std::string then please enlighten me. Also, please
disregard some of the funky spacing, as I'm trying to get it to fit on
80 character lines for the NG post.

#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#include <vector>

template <class T,
class Ch = char,
class Tr = std::char_trait s<Ch>,
class Dist = std::ptrdiff_t>
class my_istream_iter ator : public std::iterator<s td::input_itera tor_tag,
T,
Dist,
const T*,
const T&> {
public:
typedef my_istream_iter ator<T, Ch, Tr, Dist> my_t;
typedef Ch char_type;
typedef Tr traits_type;
typedef std::basic_istr eam<Ch, Tr> istream_type;

// construct singular iterator
my_istream_iter ator() : my_istream(0) { }

// construct with input stream
my_istream_iter ator(istream_ty pe& s) : my_istream(&s) { getval(); }

// return designated value
const T& operator*() const { return my_val; }

// return pointer to class object
const T* operator->() const { return &**this; }

// preincrement
my_istream_iter ator& operator++()
{
getval();
return *this;
}

// postincrement
my_istream_iter ator operator++(int)
{
my_t tmp = *this;
++*this;
return tmp;
}

// test for iterator equality
bool equal(const my_t& rhs) const { return my_istream == rhs.my_istream; }

protected:
// get a T value if possible
void getval()
{
if (my_istream != 0 && !(*my_istream >> my_val))
my_istream = 0;
}

istream_type* my_istream; // pointer to input stream
T my_val; // lookahead value (valid if my_istream is not null)
};

// specialization for std::string
template <>
void my_istream_iter ator<std::basic _string<char>, char,
std::char_trait s<char>, std::ptrdiff_t> ::getval()
{
if (my_istream != 0 && !(std::getline( *my_istream, my_val)))
my_istream = 0;
}

// my_istream_iter ator template operators
// test for my_istream_iter ator equality
template <class T, class Ch, class Tr, class Dist>
inline bool operator==(cons t my_istream_iter ator<T, Ch, Tr, Dist>& lhs,
const my_istream_iter ator<T, Ch, Tr, Dist>& rhs)
{
return lhs.equal(rhs);
}

template <class T, class Ch, class Tr, class Dist>
inline bool operator!=(cons t my_istream_iter ator<T, Ch, Tr, Dist>& lhs,
const my_istream_iter ator<T, Ch, Tr, Dist>& rhs)
{
return !(lhs == rhs);
}

int main(int argc, char* argv[])
{
std::ifstream in(argv[1]);
std::vector<std ::string> vec;

std::copy(my_is tream_iterator< std::string>(in ),
my_istream_iter ator<std::strin g>(),
std::back_inser ter(vec));

std::ofstream out(argv[2]);
std::copy(vec.b egin(),
vec.end(),
std::ostream_it erator<std::str ing>(out, "\n"));

return 0;
}

// vim: tabstop=4 shiftwidth=4

--
Marcus Kwok
Dec 2 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2159
by: NPC | last post by:
Hi, Is there any way to use an istream_iterator<> in a way which inserts each element at the end of a newline character rather than a space character? Could be it looks for any type of whitespace - not sure about that. In particular, it would be nice to use it in a way which is similar to an ostream_iterator: std::vector<std::string> myVec; /* add stuff to myVec */
103
48738
by: Steven T. Hatton | last post by:
§27.4.2.1.4 Type ios_base::openmode Says this about the std::ios::binary openmode flag: *binary*: perform input and output in binary mode (as opposed to text mode) And that is basically _all_ it says about it. What the heck does the binary flag mean? -- If our hypothesis is about anything and not about some one or more particular things, then our deductions constitute mathematics. Thus mathematics may be defined as the subject in...
2
1648
by: alberto | last post by:
I am learning STL with the book STL Tutorial and Reference guide (1 edition), the following example don't run : int main() { // Initialize array a with 10 integers: int a = {12, 3, 25, 7, 11, 213, 7, 123, 29, -31}; // Find the first element equal to 7 in the array: int* ptr = find(&a, &a, 7);
6
8486
by: George | last post by:
Hi All, I'm trying to learn c++/stl. I'd like a fancy way to read lines of an ascii file into vector of stringbufs. I made a first attempt, but the compiler complains about private constructors in streambuf. I'd like to use algorithms instead of a loop, but I don't know if that is possible. Any ideas? Thanks in advance.
3
3819
by: jmoy.matecon | last post by:
I get an error while compiling the following program: int main() { vector<int> v(istream_iterator<int>(cin), istream_iterator<int>()); copy(v.begin(),v.end(),ostream_iterator<int>(cout,"\n")); } The errors I get are is:
8
3111
by: dragoncoder | last post by:
Hi, I am just a newbie in STL and trying to learn istream_iterator. My problem is I want a program which will take a comma separated string from the command line, tokenize it and copies into a vector. Then I am printing the vector. Here is the code I tried. #include <iostream> #include <sstream> #include <vector>
5
2836
by: Pradeep | last post by:
Hi All, I am facing some problem using istream_iterator for reading the contents of a file and copying it in a vector of strings.However the same thing works for a vector of integers. The code that doesn't work is std::vector<std::stringvecStr; std::ifstream fstrRead("Test.txt");
2
1811
by: Juha Nieminen | last post by:
I'm using gcc 3.3.5. This code: std::set<std::stringt(std::istream_iterator<std::string>(std::cin), std::istream_iterator<std::string>()); gives a strange error message: error: cannot use `::' in parameter declaration If I try it this way:
9
4440
by: ahmadcorp | last post by:
Hi, This should be a simple problem, but I can't seem to figure it out. Maybe someone can help? I have a file containing data each line has about 6 entries (numbers) space delimited and each line has a new line character at the end of the line. I'd like to read the file in one pass, so I am trying to use std::istreambuf_iterator as follows (where inputFile is an ifstream):
0
9303
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9117
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9676
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9541
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7078
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4955
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5156
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3141
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2508
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.