Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::getline() to read a text file into an array of strings in C++?

I am trying to use std::getline() in my project to read in a text file into an array of strings.

Here is my code:

ifstream ifs ( path );
string * in_file;
int count = 0;
while ( !ifs.eof() )
{
    ++count;
    if ( count == 1 )
    {
        in_file = new string[1];
    }
    else
    {
            // Dynamically allocate another space in the stack
    string *old_in_file = in_file;
    in_file = new string[count];
            // Copy over values
    for ( int i = 0 ; i < ( count - 1 ) ; i++ )
    {
        in_file[i] = old_in_file[i];
    }
    delete[] old_in_file;
    }
            // After doing some debugging I know this is the problem what am I 
            // doing wrong with it?
    getline(ifs,in_file[count - 1]);
}

So after doing some decoding I know that the getline() is not placing any value in the array of strings. It seems to place a null string in the array.

The goal is to read in a text file like:

Hello
Bye
See you later

The array will be filled like:

in_file [0] = Hello
in_file [1] = Bye
in_file [2] = See you later
like image 851
user1334858 Avatar asked Oct 01 '13 18:10

user1334858


People also ask

Does Getline work with strings?

getline (string) in C++ The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.

Can Getline be used for arrays?

Getline Character Array: This function reads the whole line of text that ends with a new line or until the maximum limit is reached. getline() is the member function of istream class. Parameters: char*: Character pointer that points to the array.

How do you read a value from a file into an array?

Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.

How do you use Getline with multiple delimiters?

std::getline() does not have an option for multiple alternate delimiters. The correct way to parse this kind of input is to use the default std::getline () to read the entire line into a std::string , then construct a std::istringstream , and then parse it further, into comma-separate values.


1 Answers

Never wrap reading from the stream with the following loop:

while ( !ifs.eof() )

At some websites, you will find an example telling you to do:

while ( ifs.good() )

which is a bit better than the first loop, yet still it is quite error prone and not advisable to do. Have a look at: Why is iostream::eof inside a loop condition considered wrong?

The most common ways of reading the files are either using std::getline when reading by lines:

std::string line;
while ( std::getline(ifs, line) ) {
    if (line.empty())                  // be careful: an empty line might be read
        continue;                      
    ...
}

or simply using >> operator when reading by words or extracting concrete types (e.g. numbers):

std::string word;
while ( ifs >> word ) {               
    ...
}

And to your dynamically allocated C-style array of std::string objects: avoid dynamic allocation as much as possible. Believe me, you don't want to take care of memory management on your own. Prefer using objects with automatic storage duration. Take advantage of what the standard library provides.
As it was pointed out already: use STL containers such as std::vector instead of C-style arrays:

std::ifstream ifs(path);
std::vector<std::string> lines;

std::string line;
while ( std::getline(ifs, line) )
{
    // skip empty lines:
    if (line.empty())
        continue;

    lines.push_back(line);
}
like image 74
LihO Avatar answered Sep 20 '22 13:09

LihO