Re: reading a Text-File into Vector of Strings
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