If you want to store a comma-separate file to a string with ifstream
I think you could not do that.
Why?
Say we have this file:
one,two,three
four,five,six
seven , eight, nine
ten, ten, ten
if you use ,
as delimiter with ifstream
( getline ) function it first reads one
then two
and then three\nfour
together; because the delimiter is ,
and not newline
if you comfortable with using std::regex
it can be solve easily:
first off all you need:
std::ifstream input_file_stream( "file" ); // file stream
std::string string[ 4 ][ 3 ]; // row and column
std::regex regex( R"(\s*,\s*)" ); // regex pattern
int row = 0, column = 0;
second step:
// read from a file line-by-line
for( std::string one_line; std::getline( input_file_stream, one_line ); ){
// regex_token_iterator as splitter and delimiter is `,`
std::regex_token_iterator< std::string::iterator > first( one_line.begin(), one_line.end(), regex, -1 ), last;
// loop over each line
while( first != last ){
// each time initialize a row
string[ row ][ column++ ] = std::string( *first++ );
}
// for the next row
++row;
column = 0;
}
and finally
for( const std::string& str : string[ 0 ] ) std::cout << str << ' ';
std::cout << '\n';
for( const std::string& str : string[ 1 ] ) std::cout << str << ' ';
std::cout << '\n';
for( const std::string& str : string[ 2 ] ) std::cout << str << ' ';
std::cout << '\n';
for( const std::string& str : string[ 3 ] ) std::cout << str << ' ';
input_file_stream.close();
and the output:
one two three
four five six
seven eight nine
ten ten ten