Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > reading a Text-File into Vector of Strings

Reply
Thread Tools

reading a Text-File into Vector of Strings

 
 
arnuld
Guest
Posts: n/a
 
      09-13-2007
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 its
coontents into a vector of strings, storinig each line as separate
element in vector.
*
*/


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


/* using Pointers because 1st argument is an input file-stream and
for 2nd argument i want to take the original vector, not the copied
one.

next line is the source of error, line #22 */
void read_file( ifstream* my_file, std::vector<std::string>* svec )
{
ifstream infile;
infile.open("my_file");

/* Process File
Here
*/
}


int main()
{
std::vector<std::string> svec;
std::vector<std::string>* psvec;

std::cout << "Enter the full Path to file: "; ifstream my_file;
ifstream* p_my_file;

std::cin >> p_my_file;

read_file( p_my_file, psvec );

return 0;
}

-------- OUTPUT --------------
[arnuld@Arch64 c++]$ g++ -ansi -pedantic -Wall -Wextra ex_08-09.cpp
ex_08-09.cpp:22: error: variable or field ‘read_file’ declared void
ex_08-09.cpp:22: error: ‘ifstream’ was not declared in this scope
ex_08-09.cpp:22: error: ‘my_file’ was not declared in this scope
ex_08-09.cpp:22: error: expected primary-expression before ‘*’ token
ex_08-09.cpp:22: error: 'svec' was not declared in this scope
ex_08-09.cpp: In function 'int main()':
ex_08-09.cpp:39: error: 'ifstream' was not declared in this scope
ex_08-09.cpp:39: error: expected `;' before ‘my_file’
ex_08-09.cpp:40: error: 'p_my_file' was not declared in this scope
ex_08-09.cpp:44: error: 'read_file' was not declared in this scope
[arnuld@Arch64 c++]$


Opening the file is the 1st stage of the problem. 2nd stage will include
copying the each line as a library string into the vector. I am facing
problems at very 1st stage.

--
http://lispmachine.wordpress.com

 
Reply With Quote
 
 
 
 
Duane Hebert
Guest
Posts: n/a
 
      09-13-2007

"arnuld" <(E-Mail Removed)> wrote in message
news(E-Mail Removed)...
> 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 its
> coontents into a vector of strings, storinig each line as separate
> element in vector.
> *
> */
>
>
> #include <iostream>
> #include <fstream>
> #include <vector>
> #include <string>
>
>
> /* using Pointers because 1st argument is an input file-stream and
> for 2nd argument i want to take the original vector, not the copied
> one.
>
> next line is the source of error, line #22 */
> void read_file( ifstream* my_file, std::vector<std::string>* svec )
> {
> ifstream infile;
> infile.open("my_file");
>
> /* Process File
> Here
> */
> }


Your function is a bit strange. If the first arg is an input
file stream, why aren't you using it?
You create a new ifstream and call open with a file name?
Maybe you just want to pass the file name to the function.
Or do you want the stream to stay open after this function
finishes?

Also, you don't need a pointer to your vector. Probably
better to pass it by reference.



>
> int main()
> {
> std::vector<std::string> svec;
> std::vector<std::string>* psvec;
>
> std::cout << "Enter the full Path to file: "; ifstream my_file;
> ifstream* p_my_file;


Shouldn't ifstream be in the std namespace?


 
Reply With Quote
 
 
 
 
=?UTF-8?B?RXJpayBXaWtzdHLDtm0=?=
Guest
Posts: n/a
 
      09-13-2007
On 2007-09-13 13:11, arnuld wrote:
> 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 its
> coontents into a vector of strings, storinig each line as separate
> element in vector.
> *
> */
>
>
> #include <iostream>
> #include <fstream>
> #include <vector>
> #include <string>
>
>
> /* using Pointers because 1st argument is an input file-stream and
> for 2nd argument i want to take the original vector, not the copied
> one.
>
> next line is the source of error, line #22 */
> void read_file( ifstream* my_file, std::vector<std::string>* svec )


void read_file(std::istream& my_file, std::vector<std::string>& vec)

For these kinds of things (passing the actual object and not a copy) a
reference is preferable, unless you need to be able to pass NULL.

> {
> ifstream infile;
> infile.open("my_file");


Looking at the code in main() it looks like the file should already be
open at this point.

>
> /* Process File
> Here
> */


Look into using std::getline() for reading the contents of the file.

> }
>
>
> int main()
> {
> std::vector<std::string> svec;
> std::vector<std::string>* psvec;
>
> std::cout << "Enter the full Path to file: "; ifstream my_file;
> ifstream* p_my_file;


Don't use a pointer, "ifstream my_file;" will do.

>
> std::cin >> p_my_file;


One problem with using the >> operator here is that it will not allow
for filenames containing spaces (I seem to recall that you can set the
delimiter somehow to change this behaviour). I would use std::getline()
here too. One you have the filename use my_file.open() to open the file
(don't forget to check that it succeeded).

> Opening the file is the 1st stage of the problem. 2nd stage will include
> copying the each line as a library string into the vector. I am facing
> problems at very 1st stage.


You should probably re-read the chapter about filestreams, opening them
are quite easy, you just use the filename as argument to the constructor
or use the open() function:

std::ifstream file("myfile.txt");

or

std::ifstream file;
file.open("myfile.txt");

--
Erik Wikström
 
Reply With Quote
 
Jerry Coffin
Guest
Posts: n/a
 
      09-13-2007
In article <(E-Mail Removed)>,
http://www.velocityreviews.com/forums/(E-Mail Removed) says...

[ ... ]

> /* using Pointers because 1st argument is an input file-stream and
> for 2nd argument i want to take the original vector, not the copied
> one.


You probably don't want to use pointers here -- you almost certainly
want to use references instead. For reference (no pun intended) you
should virtually _always_ plan on passing any stream by reference.

> next line is the source of error, line #22 */
> void read_file( ifstream* my_file, std::vector<std::string>* svec )


That needs to be 'std::ifstream'.

> ex_08-09.cpp:22: error: variable or field ?read_file? declared void


Without the 'std::' on the beginning, the compiler doesn't recognize
that 'ifstream' is supposed to be a type. It's trying to read it as a
value, so it thinks you have something like:

int x(1);

but it's telling you that you can't define a variable of type 'void'.

--
Later,
Jerry.

The universe is a figment of its own imagination.
 
Reply With Quote
 
Jim Langston
Guest
Posts: n/a
 
      09-13-2007
"arnuld" <(E-Mail Removed)> wrote in message
news(E-Mail Removed)...
> 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 its
> coontents into a vector of strings, storinig each line as separate
> element in vector.
> *
> */
>
>
> #include <iostream>
> #include <fstream>
> #include <vector>
> #include <string>
>
>
> /* using Pointers because 1st argument is an input file-stream and
> for 2nd argument i want to take the original vector, not the copied
> one.
>
> next line is the source of error, line #22 */
> void read_file( ifstream* my_file, std::vector<std::string>* svec )
> {
> ifstream infile;
> infile.open("my_file");
>
> /* Process File
> Here
> */
> }
>
>
> int main()
> {
> std::vector<std::string> svec;
> std::vector<std::string>* psvec;
>
> std::cout << "Enter the full Path to file: "; ifstream my_file;
> ifstream* p_my_file;
>
> std::cin >> p_my_file;
>
> read_file( p_my_file, psvec );
>
> return 0;
> }
>
> -------- OUTPUT --------------
> [arnuld@Arch64 c++]$ g++ -ansi -pedantic -Wall -Wextra ex_08-09.cpp
> ex_08-09.cpp:22: error: variable or field 'read_file' declared void
> ex_08-09.cpp:22: error: 'ifstream' was not declared in this scope
> ex_08-09.cpp:22: error: 'my_file' was not declared in this scope
> ex_08-09.cpp:22: error: expected primary-expression before '*' token
> ex_08-09.cpp:22: error: 'svec' was not declared in this scope
> ex_08-09.cpp: In function 'int main()':
> ex_08-09.cpp:39: error: 'ifstream' was not declared in this scope
> ex_08-09.cpp:39: error: expected `;' before 'my_file'
> ex_08-09.cpp:40: error: 'p_my_file' was not declared in this scope
> ex_08-09.cpp:44: error: 'read_file' was not declared in this scope
> [arnuld@Arch64 c++]$
>
>
> Opening the file is the 1st stage of the problem. 2nd stage will include
> copying the each line as a library string into the vector. I am facing
> problems at very 1st stage.


Output of the following program on my system is:
Enter the full Path to file: c:\alcsetup.log
[ResponseResult]
ResultCode=0

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

void read_file( std::ifstream& my_file, std::vector<std::string>& svec )
{
std::string Line;
while ( std::getline( my_file, Line ) )
svec.push_back( Line );
}

int main()
{
std::vector<std::string> svec;
std::cout << "Enter the full Path to file: ";
std::string FileName;
std::cin >> FileName;
std::ifstream my_file( FileName.c_str() );
read_file( my_file, svec );

std::copy( svec.begin(), svec.end(),
std:stream_iterator<std::string>(std::cout, "\n") );

return 0;
}


 
Reply With Quote
 
arnuld
Guest
Posts: n/a
 
      09-13-2007
> On Sep 13, 4:49 pm, Erik Wikstrm <(E-Mail Removed)> wrote:
>> arnuld wrote:


> void read_file(std::istream& my_file, std::vector<std::string>& vec)
>
> For these kinds of things (passing the actual object and not a copy) a
> reference is preferable, unless you need to be able to pass NULL.


ok


> > {
> > ifstream infile;
> > infile.open("my_file");


> Looking at the code in main() it looks like the file should already be
> open at this point.


:-\


> > /* Process File
> > Here
> > */

>
> Look into using std::getline() for reading the contents of the file.


got it.


> > std::cout << "Enter the full Path to file: "; ifstream my_file;
> > ifstream* p_my_file;

>
> Don't use a pointer, "ifstream my_file;" will do.


you mean streams magically use references (stream name will be
implicitly converted to a reference ) ?


> > std::cin >> p_my_file;

>
> One problem with using the >> operator here is that it will not allow
> for filenames containing spaces (I seem to recall that you can set the
> delimiter somehow to change this behaviour). I would use std::getline()
> here too. One you have the filename use my_file.open() to open the file
> (don't forget to check that it succeeded).


ok, done


> You should probably re-read the chapter about filestreams, opening them
> are quite easy, you just use the filename as argument to the constructor
> or use the open() function:
>
> std::ifstream file("myfile.txt");
>
> or
>
> std::ifstream file;
> file.open("myfile.txt");
>


you want to say that fstream is like a library String ?

To manipulate the string 1st you have to create a String using:
std::string a_string;

looks like I have to treat an I/O Stream like a library String. I
thought I/O streams exist automatically, as this is the place where I
type program all the time, using Emacs.

 
Reply With Quote
 
arnuld
Guest
Posts: n/a
 
      09-13-2007
> On Sep 13, 6:22 pm, Jerry Coffin <(E-Mail Removed)> wrote:

> You probably don't want to use pointers here -- you almost certainly
> want to use references instead. For reference (no pun intended) you
> should virtually _always_ plan on passing any stream by reference.



> ex_08-09.cpp:22: error: variable or field ?read_file? declared void
>
> Without the 'std::' on the beginning, the compiler doesn't recognize
> that 'ifstream' is supposed to be a type. It's trying to read it as a
> value, so it thinks you have something like:
>
> int x(1);
>
> but it's telling you that you can't define a variable of type 'void'.


thanks Jerry, I learned 2 very-important things today

 
Reply With Quote
 
=?ISO-8859-1?Q?Erik_Wikstr=F6m?=
Guest
Posts: n/a
 
      09-13-2007
On 2007-09-13 18:58, arnuld wrote:
>> On Sep 13, 4:49 pm, Erik Wikstrm <(E-Mail Removed)> wrote:
>>> arnuld wrote:

>
>> void read_file(std::istream& my_file, std::vector<std::string>& vec)
>>
>> For these kinds of things (passing the actual object and not a copy) a
>> reference is preferable, unless you need to be able to pass NULL.

>
> ok
>
>
>> > {
>> > ifstream infile;
>> > infile.open("my_file");

>
>> Looking at the code in main() it looks like the file should already be
>> open at this point.

>
> :-\
>
>
>> > /* Process File
>> > Here
>> > */

>>
>> Look into using std::getline() for reading the contents of the file.

>
> got it.
>
>
>> > std::cout << "Enter the full Path to file: "; ifstream my_file;
>> > ifstream* p_my_file;

>>
>> Don't use a pointer, "ifstream my_file;" will do.

>
> you mean streams magically use references (stream name will be
> implicitly converted to a reference ) ?


Not sure what you mean here. The reason you don't need a pointer is that
the lifetime of the istream is equal to the function in which is
declared (main()) so there's really no need to have it on the heap.
Allocating on the heap is usually only needed if the variable have a
lifetime incompatible with the lifetime of the scope in which it is
declared. This way you also don't have to worry about deleting it when
you are done with it.

>> > std::cin >> p_my_file;

>>
>> One problem with using the >> operator here is that it will not allow
>> for filenames containing spaces (I seem to recall that you can set the
>> delimiter somehow to change this behaviour). I would use std::getline()
>> here too. One you have the filename use my_file.open() to open the file
>> (don't forget to check that it succeeded).

>
> ok, done
>
>
>> You should probably re-read the chapter about filestreams, opening them
>> are quite easy, you just use the filename as argument to the constructor
>> or use the open() function:
>>
>> std::ifstream file("myfile.txt");
>>
>> or
>>
>> std::ifstream file;
>> file.open("myfile.txt");
>>

>
> you want to say that fstream is like a library String ?
>
> To manipulate the string 1st you have to create a String using:
> std::string a_string;
>
> looks like I have to treat an I/O Stream like a library String. I
> thought I/O streams exist automatically, as this is the place where I
> type program all the time, using Emacs.


ifstream is just another class in the library and have to be created
just like any other object. The only streams that do not have to be
created before use are std::cin, std::cout, std::cerr, and std::clog.

--
Erik Wikstrm
 
Reply With Quote
 
BobR
Guest
Posts: n/a
 
      09-13-2007

arnuld <(E-Mail Removed)> wrote in message...
> 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 its
> coontents into a vector of strings, storinig each line as separate
> element in vector.
> */
>
> #include <iostream>
> #include <fstream>
> #include <vector>
> #include <string>
>
> /* using Pointers because 1st argument is an input file-stream and
> for 2nd argument i want to take the original vector, not the copied
> one. next line is the source of error, line #22 */
> void read_file( ifstream* my_file, std::vector<std::string>* svec ){
> ifstream infile;
> infile.open("my_file");
> /* Process File Here */
> }


void read_file( std::string const &my_file, std::vector<std::string>
&svec ){
std::ifstream infile( my_file.c_str() );
if( not infile.is_open() ){ /* error */ }
/* Process File Here */
}

> int main(){
> std::vector<std::string> svec;

// > std::vector<std::string>* psvec;
>
> std::cout << "Enter the full Path to file: "; ifstream my_file;

// > ifstream* p_my_file;
// > std::cin >> p_my_file;

std::string p_my_file;
std::getline( std::cin, p_my_file );

// > read_file( p_my_file, psvec );
read_file( p_my_file, svec );

> return 0;
> }


If you really did want to do what you were thinking, don't limit your
function.

void read_file( std::istream &in, std::vector<std::string> &svec ){
// note: that is 'istream', not 'ifstream'.
for( std::string line; std::getline( in, line ); /*m_t*/ ){
svec.push_back( line );
} // for(line)
return;
} // read_file(istream&,vector<string>&)

int main(){
std::vector<std::string> svec;
std::ifstream infile( "MyFile.txt" );
std::istringstream instring( "This will \n simulate \n" ); // <sstream>

read_file( infile, svec );
read_file( instring, svec );
std::cout<<"Type in some lines"<<std::endl;

/* I'll leave it to you to figure a way to invoke/terminate
input on this one <G>*/
/* hint: ctrl-Z, ctrl-C, [return], as-is, ??? */
read_file( std::cin, svec );

std::copy( svec.begin(), svec.end(),
std:stream_iterator<std::string>( std::cout, "\n" ) );

return 0;
} // main()

Don't complicate your programming with pointers, unless you are *forced* to.
:-}

--
Bob R
POVrookie


 
Reply With Quote
 
Juha Nieminen
Guest
Posts: n/a
 
      09-13-2007
arnuld wrote:
> void read_file( ifstream* my_file, std::vector<std::string>* svec )
> {
> ifstream infile;
> infile.open("my_file");


I feel from your code that you lack basic understanding of C++ types,
pointers, and how they work and are used.

I wonder if you even understand what "ifstream" is and what
"ifstream*" means.

In that function you create a new ifstream and then open it,
suspiciously with the same name as your first function parameter, ie.
"my_file". This makes me suspect that you think that you are opening
that "file" represented by the first function parameter, called
"my_file", by giving the name of that variable, as a string none the
less, to a second ifstream.

The variable named my_file and the string "my_file" have *nothing*
to do with each other. They have absolutely no relation. One is a
variable (in this case of type "pointer-to-ifstream") and the other is
a string literal. Just because the string literal has the same
characters as the name of that variable don't make them related in any way.

Just the fact that you seem to try to be opening an ifstream with
another ifstream seems to show that you don't really understand what the
ifstream class is.

> std::vector<std::string> svec;
> std::vector<std::string>* psvec;


You do understand that psvec is *not* a vector, but a pointer (and
nothing more than a pointer), and that you are not even making it to
point anywhere? psvec is basically an uninitialized pointer (which could
point basically anywhere and will most probably cause a crash if you try
to read/write it).

svec *is* a vector, but you are not using it for anything. I'm just
wondering what exactly is it that you expect those two lines to mean.

If you want to have a vector (such as svec above), you don't need to
explicitly create a pointer in order to be able to pass that vector to
a function as a pointer (or, preferably, as a reference). There's no
need to explicitly create a pointer just to do that.

For example, let's assume we have somewhere a function like this:

void foo(std::vector<std::string>& aVector) { ... }

This takes a vector as reference. In other words, a copy of the vector
is *not* given to this function when it's called, but instead just a
reference to the original vector. (You can think of references as
limited pointers.)

Somewhere else you could write this:

std::vector<std::string> myVector;
foo(myVector);

The first line creates an vector, and the second line calls the foo()
function giving that vector as parameter. But as already seen, the
function doesn't actually take a copy of the vector, but a reference to
it, and thus any modification the function makes to that vector will be
done to the 'myVector' vector.

You could, of course, pass a pointer to your original vector too
(although a reference is usually recommended). In that case you make the
function to take a pointer:

void foo(std::vector<std::string>* aVector) { ... }

and then you can call it like this:

std::vector<std::string> myVector;
foo(&myVector);

The & operator means "create a pointer pointing to this variable".
Thus the foo() function is given a pointer to 'myVector', and if foo()
modifies the vector behind the pointer, 'myVector' will be modified.

In neither case you need to explicitly create a pointer variable,
like you did. (And even if you created one, you would have to,
naturally, make it point somewhere and not leave it uninitialized like
you did.)

> std::cout << "Enter the full Path to file: "; ifstream my_file;


I'm left wondering why you put those two things in the same line.
Was it just an oversight, or are you trying to express some relation
between the two things? (Because there isn't, of course.)

And again, you create an ifstream variable, and immediately after that
(below) an uninitialized pointer of the same type. It strongly seems
that you expect some kind of relation between them, although there is
none. 'my_file' and 'p_my_file' are two different variables. They have
no relation to each other. (There could be some relation if you put the
latter to point to the former, but you didn't even do that.)

> ifstream* p_my_file;
>
> std::cin >> p_my_file;


This, again, seems to show that you don't really understand what
ifstream is.

First you ask for a file *name*, in other words, a *string*, and then
you try to read that name directly into the ifstream pointer.

An ifstream is not a string. It's a class which you can use to read a
file. You can't ask the user for a string and somehow read it into an
ifstream, much less into an ifstream *pointer*. (Again, a pointer is
*not* an ifstream, it's just a pointer. Internally it's nothing more
than a memory address. It's *not* an instance of an ifstream class.)

What you want is to read a *string* from the user, and then use that
to open the file. Something like this:

std::string fileName;
std::cin >> fileName;
std::ifstream inputFileStream;
inputFileStream.open(fileName.c_str());

(The ".c_str()" part is necessary because, for whatever reason, the
C++ standard committee decided that ifstream will not support a
std::string directly. Anyways, it's largely irrelevant here. For now,
just memorize this little annoyance.)

Btw, the last two lines could be shortened to:

std::ifstream inputFileStream(fileName.c_str());

Reading the lines in the file into the vector can be done in a
relatively simple way, using the std::getline() function in a loop.
For example, something like this:

std::vector<std::string> lines;
std::string line;

while(inputFileStream.good())
{
std::getline(inputFileStream, line);
lines.push_back(line);
}

That's it. It doesn't need to be more complicated than that.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
const vector<A> vs vector<const A> vs const vector<const A> Javier C++ 2 09-04-2007 08:46 PM
Initializing vector<vector<int> > and other vector questions... pmatos C++ 6 04-26-2007 05:39 PM
Free memory allocate by a STL vector, vector of vector, map of vector Allerdyce.John@gmail.com C++ 8 02-18-2006 12:48 AM
how the vector is created, how to pass vector to webservices method apachesoap:Vector Rushikesh Joshi Perl Misc 0 07-10-2004 01:04 PM
Reading Blank Lines into StringTokens into Vector Array Row Java 0 04-14-2004 07:12 AM



Advertisments