0

I am not able to store the string from Excel into a 2-d string.

#include <iostream>
#include <string.h>
#include <fstream>   
#include <sstream>
using namespace std;

int main()
{
    ifstream file("input.csv");
    string line,cell;
    string name[5][20];
    string period[5][8];
    string tname;
    int pos, i = 0;

    while(getline(file, line)) {
        stringstream linestream(line);
        int j = 0;
        while(getline(linestream, cell, ',')) {
            if(j == 0)
                name[i][j] = cell;
            else
                period[i][j - 1] = cell;
            j++;
        }
        i++;
    }
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

1 Answers1

0

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
Shakiba Moshiri
  • 21,040
  • 2
  • 34
  • 44