473,406 Members | 2,713 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Reading items from a text file to a vector

zr
Hi,

i need to read a text file which contains a list of items, all of type
ItemType, separated by whitespace and newlines. For each line, there
will be a vector<ItemTypeobject that will store the integers read in
that line. There will be a single vector<vector<ItemType>object that
will stores all of the vector<ItemTypeobjects mentioned in the
previous sentence.
I wrote a quick implementation and it seems to be working, but i would
like to hear some opinions on what may be incorrect or may be
improved, especially exception and runtime error handling. Assume that
the required operator>in code line 13 is defined.

TIA

1 template <class ItemType>
2 void collect(istream& source, vector<vector<ItemType>>& db) {
3 while (source.good()) {
4 string s;
5 getline(source, s, '\n');
6 istringstream iss(s);
7 if (iss.bad() || 0==s.size())
8 break;
9 vector<ItemTypet;
10
11 while (iss.good()) {
12 ItemType item;
13 iss >item;
14 t.push_back(item);
15 }
16 db.push_back(t);
17 }
18}

Nov 14 '08 #1
4 2260
zr wrote:
Hi,

i need to read a text file which contains a list of items, all of type
ItemType, separated by whitespace and newlines. For each line, there
will be a vector<ItemTypeobject that will store the integers read in
that line. There will be a single vector<vector<ItemType>object that
will stores all of the vector<ItemTypeobjects mentioned in the
previous sentence.
I wrote a quick implementation and it seems to be working, but i would
like to hear some opinions on what may be incorrect or may be
improved, especially exception and runtime error handling. Assume that
the required operator>in code line 13 is defined.
Don't use line numbers in your posts. It makes it difficult for
readers to cut&paste your code.
Correction on your line2 and on your lines 11-15.

>
1 template <class ItemType>
2 void collect(istream& source, vector<vector<ItemType>>& db) {
vector<vector<ItemType& db
3 while (source.good()) {
4 string s;
5 getline(source, s, '\n');
6 istringstream iss(s);
7 if (iss.bad() || 0==s.size())
8 break;
9 vector<ItemTypet;
10
11 while (iss.good()) {
12 ItemType item;
13 iss >item;
14 t.push_back(item);
15 }
for (ItemType item; iss >item; )
t.push_back(item);

16 db.push_back(t);
17 }
18}
Nov 14 '08 #2
red floyd wrote:
zr wrote:
>Hi,

i need to read a text file which contains a list of items, all of type
ItemType, separated by whitespace and newlines. For each line, there
will be a vector<ItemTypeobject that will store the integers read in
that line. There will be a single vector<vector<ItemType>object that
will stores all of the vector<ItemTypeobjects mentioned in the
previous sentence.
I wrote a quick implementation and it seems to be working, but i would
like to hear some opinions on what may be incorrect or may be
improved, especially exception and runtime error handling. Assume that
the required operator>in code line 13 is defined.
Don't use line numbers in your posts. It makes it difficult for
readers to cut&paste your code.
Correction on your line2 and on your lines 11-15.
Forgot the correction on 3-5.
>
>>
1 template <class ItemType>
2 void collect(istream& source, vector<vector<ItemType>>& db) {
vector<vector<ItemType& db
>3 while (source.good()) {
4 string s;
5 getline(source, s, '\n');
for (string s; getline(source, s); ) // '\n' is implied
>6 istringstream iss(s);
7 if (iss.bad() || 0==s.size())
8 break;
9 vector<ItemTypet;
10
>11 while (iss.good()) {
12 ItemType item;
13 iss >item;
14 t.push_back(item);
15 }
for (ItemType item; iss >item; )
t.push_back(item);

>16 db.push_back(t);
17 }
18}
Nov 14 '08 #3
On Nov 14, 2:00 am, zr <zvir...@gmail.comwrote:
i need to read a text file which contains a list of items, all
of type ItemType, separated by whitespace and newlines. For
each line, there will be a vector<ItemTypeobject that will
store the integers read in that line. There will be a single
vector<vector<ItemType>object that will stores all of the
vector<ItemTypeobjects mentioned in the previous sentence.
I wrote a quick implementation and it seems to be working, but
i would like to hear some opinions on what may be incorrect or
may be improved, especially exception and runtime error
handling. Assume that the required operator>in code line 13
is defined.
As you've posted it, it won't compile:-). But in fact, it isn't
guaranteed to work, even with the correction to the syntax.
1 template <class ItemType>
2 void collect(istream& source, vector<vector<ItemType>>& db) {
">>" is a shift left operator, and doesn't close two open template
lists; you need "" (unless your compiler has already
implemented this feature of the next version of the standard).
3 while (source.good()) {
And this is an error; source.good() does NOT mean that the next
input is guaranteed to succeed. (In practice, what will
probably happen is that you'll get an extra, empty list at the
end of your results.)
4 string s;
5 getline(source, s, '\n');
6 istringstream iss(s);
7 if (iss.bad() || 0==s.size())
8 break;
9 vector<ItemTypet;
10
11 while (iss.good()) {
Same thing here. Most of the time, this will work anyway, but
if you have a line which contains trailing white space, it may
result in an additional default constructed item at the end of
the list.
12 ItemType item;
13 iss >item;
14 t.push_back(item);
15 }
16 db.push_back(t);
17 }
18}
In general, you should always test *after* reading from a
stream, to know if the input succeeded or failed. And be wary
of the names of the status functions in the streams; they are
very misleading. (I've never found a use for good(), for
example.) Taking this into account, your code should probably
look something like:

std::string s ;
while ( std::getline( source, s ) ) {
std::istringstream iss( s ) ;
std::vector< ItemType >
t ;
ItemType item ;
while ( iss >item ) {
t.push_back( item ) ;
}
db.push_back( t ) ;
}

In addition, you might want to think about other possible input
errors: what happens if an item in the file is misformatted.
(You can typically detect this by checking iss.eof() after the
inner loop above; if input failed and you don't have eof() or
bad(), then you have a formatting error.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 14 '08 #4
zr wrote:
Hi,

i need to read a text file which contains a list of items, all of type
ItemType, separated by whitespace and newlines. For each line, there
will be a vector<ItemTypeobject that will store the integers read in
that line. There will be a single vector<vector<ItemType>object that
will stores all of the vector<ItemTypeobjects mentioned in the
previous sentence.
I wrote a quick implementation and it seems to be working, but i would
like to hear some opinions on what may be incorrect or may be
improved, especially exception and runtime error handling. Assume that
the required operator>in code line 13 is defined.

TIA

1 template <class ItemType>
2 void collect(istream& source, vector<vector<ItemType>>& db) {
3 while (source.good()) {
4 string s;
5 getline(source, s, '\n');
6 istringstream iss(s);
7 if (iss.bad() || 0==s.size())
8 break;
9 vector<ItemTypet;
10
11 while (iss.good()) {
12 ItemType item;
13 iss >item;
14 t.push_back(item);
15 }
16 db.push_back(t);
17 }
18}
You have received some suggestions so far. The following is radically
different: (a) globally and (b) locally.

(a) The two problems of converting a single line and converting a whole file
are intermingled in your solution. I suggest taking those issues apart.
Also, you deal with vectors of vectors specifically. I think, one can be
more general.

(b) Just for fun, I used iterators and standard algorithms. Two different
methods of error reporting are employed: exceptions if there is no stream
to return or the status bits of the stream if present.

Here goes:

#include <iostream>
#include <istream>
#include <string>
#include <iterator>
#include <vector>
#include <algorithm>
#include <sstream>
#include <stdexcept>

struct line : public std::string {};

std::istream & operator>( std::istream & istr, line & l ) {
return ( std::getline( istr, l ) );
}

template < typename Sequence >
Sequence scan_line ( std::string const & l ) {
std::istringstream istr ( l );
Sequence result;
typedef typename Sequence::value_type value_type;
std::copy( std::istream_iterator< value_type >( istr ),
std::istream_iterator< value_type >(),
std::back_inserter( result ) );
if ( ! istr.eof() || istr.bad() ) {
throw ( std::invalid_argument( "line invalid\n" ) );
}
return ( result );
}

template < typename Sequence >
std::istream & collect ( std::istream & istr, Sequence & seq ) {
typedef typename Sequence::value_type value_type;
std::transform( std::istream_iterator< line >( istr ),
std::istream_iterator< line >(),
std::back_inserter( seq ),
& scan_line< value_type );
return ( istr );
}

int main ( void ) {
std::vector< std::vector<int ivv;
try {
collect( std::cin, ivv );
if ( std::cin.eof() && ! std::cin.bad() ) {
for ( unsigned long n = 0; n < ivv.size(); ++n ) {
for ( unsigned long m = 0; m < ivv[n].size(); ++m ) {
std::cout << ivv[n][m] << " ";
}
std::cout << "\n";
}
} else {
std::cerr << "File format error\n";
}
}
catch ( std::invalid_argument const & i ) {
std::cerr << i.what();
}
}
BTW: I do not claim that this is "better". I just think you should know that
there are many ways to go about this.
Best

Kai-Uwe Bux
Nov 15 '08 #5

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

Similar topics

0
by: Row | last post by:
HI, I would first like to say its been about 3 years since looking at java im very rusty! I have to write a post it notes type applet which will function online. (reading from a flat text file)...
7
by: Santah | last post by:
hi I'm new to C++ and I'm currently working on Visual C++ 6.0 I'm trying to open a text file, and read some data from it part of the text file looks like this: --------
4
by: nightflyer | last post by:
Hi all, [code snippet appended at the end.) my question: A class has a few string variables with not know length at design time. Now I declare lets say a 1000 of those classes and put them...
19
by: Lionel B | last post by:
Greetings, I need to read (unformatted text) from stdin up to EOF into a char buffer; of course I cannot allocate my buffer until I know how much text is available, and I do not know how much...
0
by: Eric Lilja | last post by:
Hello, I have a text file that contains a number of entries describing a recipe. Each entry consists of a number of strings. Here's an example file with only one entry (recipe): Name=Maple Quill...
8
by: Darsant | last post by:
I'm currently reading 1-n number of binary files, each with 3 different arrays of floats containing about 10,000 values a piece for a total of about 30,000 values per file. I'm looking for a way...
3
by: The Cool Giraffe | last post by:
Regarding the following code i have a problem. void read () { fstream file; ios::open_mode opMode = ios::in; file.open ("some.txt", opMode); char *ch = new char; vector <charv; while...
9
by: Eric Lilja | last post by:
Hi! I have a program with a class that needs to be able to write itself to a file in clear text format. The file has two integers and vector of struct objects. The struct has a string that can...
15
by: arnuld | last post by:
This is the partial-program i wrote, as usual, i ran into problems halfway: /* C++ Primer - 4/e * * Exercise 8.9 * STATEMENT: * write a function to open a file for input and then read...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...

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.