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 some decoding, I know that getline () does not put any value in an array of strings. It seems to put a null string into the array.

The goal is to read a text file, for example:

 Hello Bye See you later 

The array will be filled as:

 in_file [0] = Hello in_file [1] = Bye in_file [2] = See you later 
+6
source share
2 answers

Never carry over reading from a stream with the following loop:

 while ( !ifs.eof() ) 

On some websites you will find an example that you should do:

 while ( ifs.good() ) 

which is slightly better than the first cycle, but still it is quite error prone and not recommended. Look at: Why is iostream :: eof inside a loop condition considered wrong?

The most common ways to read files are either using std::getline when reading line by line:

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

or simply using the >> operator when reading in words or extracting specific 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 do not want to take care of managing your memory on your own. Prefer to use objects with automatic storage time. Take advantage of the standard library. As already stated: use STL containers like 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); } 
+6
source

Why so unpleasant?

Just use std:vector for std::string

 std::string str; std::vector <std::string> vec; while ( std::getline(ifs,str) ) { vec.push_back(str) ; } 

If you really need a string array

do:

string * in_file = new string[vec.size()];

And copy the elements from vec to in_file

 for(size_t i=0;i<vec.size();i++) in_file[i] = vec[i]; 
+10
source

Source: https://habr.com/ru/post/955052/


All Articles