c++ - I am not able store the input string from Excel into 2-dimensional string -


i not able store string excel 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, = 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++;     } 

if want store comma-separate file string ifstream think not that.
why?

say have file:

one,two,three four,five,six 7   ,  eight, 9 ten,    ten,   ten   

if use , delimiter ifstream ( getline ) function first reads one two , three\nfour together; because delimiter , , not newline

if comfortable using std::regex can solve easily:

first off need:

std::ifstream input_file_stream( "file" ); // file stream std::string string[ 4 ][ 3 ];              // row , column std::regex regex( r"(\s*,\s*)" );          // regex pattern int row = 0, column = 0;   

second step:

// read file line-by-line for( std::string one_line; std::getline( input_file_stream, one_line ); ){      // regex_token_iterator splitter , delimiter `,`     std::regex_token_iterator< std::string::iterator > first( one_line.begin(), one_line.end(), regex, -1 ), last;          // loop on each line         while( first != last ){              // each time initialize row             string[ row ][ column++ ] = std::string( *first++ );         }          // 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 output:

one 2 3  4 5 6  7 8 9  ten ten ten 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -