473,240 Members | 1,650 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,240 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 8111


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...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...

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.