473,387 Members | 1,463 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,387 software developers and data experts.

Reading file input into a string vector

Hi everyone...
I'm pretty much a newbie C++ user, and I've run into a problem.
I'm trying to read in a large text file, and then do manipulations on
it. I can read it into a large 2-dimensional character array, but I'd
really like to read it into a vector of strings. Here's how I'm doing
the read into the char array:

int main() {
string str1("booger");
string str2("test");
int index = 0;
char buffer[256]; //two dimensional string
array
char buff2[1000][256]; // 1K lines, 256
chars each
ifstream examplefile ("example.txt"); //test file
if (! examplefile.is_open()) //check to make
sure file can be opened
{ cout << "Error opening file"; exit (1); }
cout << str1 << "\n\n";
while (! examplefile.eof() ) //do until end of
file is reached
{
examplefile.getline (buff2[index],100); //get the
line, put into buffer
cout << "buffer:" << buff2[index] << endl; //print out
the contents of buffer
index = index + 1;
}
return 0;
}

So that works out great...but I'm not sure how I'd modify that to
replace the char buffer[] with a string vector. Any hints for me?

Thanks in advance...

dave
Jul 23 '05 #1
6 8116


Dave Reid wrote:
Hi everyone...
I'm pretty much a newbie C++ user, and I've run into a problem.
I'm trying to read in a large text file, and then do manipulations on
it. I can read it into a large 2-dimensional character array, but I'd
really like to read it into a vector of strings. Here's how I'm doing
the read into the char array:

int main() {
string str1("booger");
string str2("test");
int index = 0;
char buffer[256]; //two dimensional string
array
char buff2[1000][256];
You just need to replace this with:

std::vector<std::string> buff2(1000);

The rest of your code shouldn't need to change, unless i mised
something.

hope this hlpes,
-shez-


// 1K lines, 256 chars each
ifstream examplefile ("example.txt"); //test file
if (! examplefile.is_open()) //check to make
sure file can be opened
{ cout << "Error opening file"; exit (1); }
cout << str1 << "\n\n";
while (! examplefile.eof() ) //do until end of
file is reached
{
examplefile.getline (buff2[index],100); //get the
line, put into buffer
cout << "buffer:" << buff2[index] << endl; //print out
the contents of buffer
index = index + 1;
}
return 0;
}

So that works out great...but I'm not sure how I'd modify that to
replace the char buffer[] with a string vector. Any hints for me?

Thanks in advance...

dave


Jul 23 '05 #2
"Shezan Baig" <sh************@gmail.com> wrote in
news:11*********************@o13g2000cwo.googlegro ups.com:
char buff2[1000][256];


You just need to replace this with:

std::vector<std::string> buff2(1000);

The rest of your code shouldn't need to change, unless i mised
something.


I'd already tried that...and I get compilation errors.

]$ g++ readfile.cc
readfile.cc: In function `int main ()':
readfile.cc:22: no matching function for call to `ifstream::getline
(basic_string<char, string_char_traits<char>,
__default_alloc_template<true, 0> > &, int)'
/usr/include/g++-3/iostream.h:129: candidates are: istream
&istream::getline (char *, int, char = '\n')
/usr/include/g++-3/iostream.h:131: istream
&istream::getline (unsigned char *, int, char = '\n')
/usr/include/g++-3/iostream.h:136: istream
&istream::getline (signed char *, int, char = '\n')

dave
Jul 23 '05 #3

"Dave Reid" <dd****@comcast.net> wrote in message
news:d7**********@gnus01.u.washington.edu...
Hi everyone...
I'm pretty much a newbie C++ user, and I've run into a problem.
I'm trying to read in a large text file, and then do manipulations on
it. I can read it into a large 2-dimensional character array, but I'd
really like to read it into a vector of strings. Here's how I'm doing
the read into the char array:

int main() {
string str1("booger");
string str2("test");
int index = 0;
char buffer[256]; //two dimensional string
array
char buff2[1000][256]; // 1K lines, 256
chars each
ifstream examplefile ("example.txt"); //test file
if (! examplefile.is_open()) //check to make
sure file can be opened
{ cout << "Error opening file"; exit (1); }
cout << str1 << "\n\n";
while (! examplefile.eof() ) //do until end of
file is reached
{
examplefile.getline (buff2[index],100); //get the
line, put into buffer
cout << "buffer:" << buff2[index] << endl; //print out
the contents of buffer
index = index + 1;
}
return 0;
}

So that works out great...but I'm not sure how I'd modify that to
replace the char buffer[] with a string vector. Any hints for me?

Thanks in advance...

dave


Write a class that does this for you. Lets call it FileParser:

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

class FileParser
{
// members
std::string s_filename;
std::string s_buffer;
std::ifstream ifs;
std::vector<std::string> vs;
public:
// ctor and d~tor
FileParser(std::string s) : s_filename(s), s_buffer(), ifs(), vs() { }
~FileParser() { }

void read( )
{
ifs.open(s_filename.c_str(), std::ios::in);
if (!ifs)
{
// todo: std::cout an open_fstream_error or throw exception
}
while ( std::getline( ifs, s_buffer ) )
{
vs.push_back(s_buffer);
}
if (!ifs.eof()) // if reason of termination != eof
{
// todo: std::cout a read_fstream_error or throw exception
}
} // read()

void display() const
{
std::copy( vs.begin(),
vs.end(),
std::ostream_iterator<std::string>( std::cout,
"\n" ) );
} // display

}; // class FileParser

int main()
{
FileParser fileparser("data.dat"); // todo: specify your target
fileparser.read();

// you may need to parse the vector
// if what you want is words, not lines
// do it in the class with a member function
// (hint: #include <sstream> and use a std::stringstream)

fileparser.display();

return 0;
}

By the way, the read()'s procedure:

a) open file and check for error. (note: if(!ifs.good()) {...} is ok as
well)
b) loop std::getline until it fails
c) verify if fstream failure was not an eof error
d) no need to ifs.close() unless you need to open it again

is standard practice. That i owe to the extraordinary ppl that populate this
newsgroup (thanks !!).

Jul 23 '05 #4
Dave Reid wrote:
"Shezan Baig" <sh************@gmail.com> wrote in
news:11*********************@o13g2000cwo.googlegro ups.com:
char buff2[1000][256];

You just need to replace this with:

std::vector<std::string> buff2(1000);

The rest of your code shouldn't need to change, unless i mised
something.


I'd already tried that...and I get compilation errors.

]$ g++ readfile.cc
readfile.cc: In function `int main ()':
readfile.cc:22: no matching function for call to `ifstream::getline
(basic_string<char, string_char_traits<char>,
__default_alloc_template<true, 0> > &, int)'
/usr/include/g++-3/iostream.h:129: candidates are: istream
&istream::getline (char *, int, char = '\n')
/usr/include/g++-3/iostream.h:131: istream
&istream::getline (unsigned char *, int, char = '\n')
/usr/include/g++-3/iostream.h:136: istream
&istream::getline (signed char *, int, char = '\n')

dave


Use the getline from <string>. See the STL docs for details:

std::getline(some_ifstream, some_std_string, some_OPTIONAL_delimiter)

e.g.:

// get everything from 'examplefile' up to the next newline
// into the std::string 'buff2[index]'. the newline is dropped.
std::getline(examplefile, buff2[index]);

// get everything from 'examplefile' up to the next SPACE char
// into the std::string 'buff2[index]'. the SPACE char is dropped.
std::getline(examplefile, buff2[index], ' ');

Regards,
Larry

--
Anti-spam address, change each 'X' to '.' to reply directly.
Jul 23 '05 #5
Dave Reid wrote:
Hi everyone...
I'm pretty much a newbie C++ user, and I've run into a problem.
I'm trying to read in a large text file, and then do manipulations on
it. I can read it into a large 2-dimensional character array, but I'd
really like to read it into a vector of strings.
The vector version is far easier:

std::vector<std::string> vec;
std::string s;
while ( std::getline(examplefile, s) )
vec.push_back(s);

The main point here is std::getline which is used for getting
a std::string from a stream, whereas istream::getline is used for
getting characters up to a certain length etc. as you found out.

FWIW I'll give you some advice on your original code:

int main() {
string str1("booger");
string str2("test");
int index = 0;
char buffer[256]; //two dimensional string array
I hope you know that that was not a 2-d string array!
char buff2[1000][256];
ifstream examplefile ("example.txt");
if (! examplefile.is_open())
{ cout << "Error opening file"; exit (1); }
It's good to avoid exit() in C++, because it won't destroy
any objects correctly (eg. examplefile won't be destroyed).
Instead, return a value from main, or throw an exception.
cout << str1 << "\n\n";
while (! examplefile.eof() ) //do until end of file is reached
But what if end of file is reached during the getline
call below? Then your program will operate on garbage until
it gets around to the start of the loop again.

The correct technique is to check the getline call itself for failure.
{
examplefile.getline (buff2[index],100);
I guess you know that this will break up any lines that are
longer than 99 characters. (NB. buff2 has lines of size
256, why are you reading 100?)
cout << "buffer:" << buff2[index] << endl;
index = index + 1;
What about when index exceeds 1000?
}
return 0;
}


Jul 23 '05 #6
In article <d7**********@gnus01.u.washington.edu>,
Dave Reid <dd****@comcast.net> wrote:

I'm trying to read in a large text file, and then do manipulations on
it. I can read it into a large 2-dimensional character array, but I'd
really like to read it into a vector of strings.


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

using namespace std;

int main ()
{
// Declare the vector with zero size initially and let it grow as needed.

vector<string> linevec;
string line;
ifstream infile ("foo.txt");

// Read the file one line at a time. The loop terminates when it tries to
// read past the end of the file. push_back() extends the vector by one
// position and copies the given string into the newly-created position.
// This way, you don't have to worry about how big to make the vector
// initially, or about what to do if the vector overflows.

// NOTE: It is almost never correct to use eof() to control an input
// loop, because it becomes true only *after* you have tried to read past
// the end of file and *failed*.

while (getline (infile, line))
{
linevec.push_back (line);
}

// See what we've read in.

for (int k = 0; k < linevec.size(); ++k)
{
cout << linevec[k] << endl;
}

return 0;
}

--
Jon Bell <jt****@presby.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Jul 23 '05 #7

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: --------
2
by: adpsimpson | last post by:
Hi, I have a file which I wish to read from C++. The file, created by another programme, contains both text and numbers, all as ascii (it's a .txt file). A sample of the file is shown below: <<...
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...
18
by: Michael | last post by:
Hi, I moved to c++ from c, and wanted to know what the best way to read data from files is in c++. Any thoughts? fscanf() is possible but fairly painful! Regards Michael
3
by: Max | last post by:
Yea this is probably a n00b question, but I haven't programmed C++ in at least 2 years and have never programmed for unix, sorry :) Anyway, I have a project in which a program is required to read...
11
by: tmshaw | last post by:
I'm a newb in a c++ class... I need to read the standard input into a couple strings. Then determine whether or not the same word is used IN SUCCESSION (ex. this cat cat is really mean.). ...
2
by: david.crow | last post by:
Given the following input file: bob 1 2 3 4 5 mary 2 3 4 5 6 7 susan 3 4 5 6 7 8 9 This code snippet does not read it correctly: class Student {
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...
4
by: zr | last post by:
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...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.