Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5284

C/C++ • Re: Two-dimensional array of character strings in C

$
0
0
Thanks works a treat added the following function
Glad you are making progress. You may have good reason to use C but I would still suggest that C++ might be a better option.
Malloc and pointer work well in the right hands but might be less maintainable.

I have used this data file

Code:

a1,a2,a3,a4b1,b2,b3,b4,b5c1,c2,c3
and this code

Code:

#include <iostream>#include <string>#include <vector>#include <fstream>#include <sstream>// to avoid lengthy declarations these types can be defined// using is like typedef// vectors are like arrays but of variable lengthusing item = std::string;// data items are stringsusing line = std::vector<item>; // a line (row) of data itemsusing table = std::vector<line>;// data table - items can be accessed as data[row][column]void output(table& data,std::ostream& file)//output the table to a file (use same format to different files){for(unsigned i = 0; i < data.size() ; i++){for(unsigned j = 0; j < data[i].size() ; j++)file << data[i][j] << "    ";file << "\n";}}int main(){table data;// this will contain the datastd::fstream infile;// data is read from data.txtinfile.open("data.txt",std::ios::in);while(!infile.eof()){std::string l;infile >> l;// read one linestd::stringstream  file(l);// turn line into fileline newline;while(!file.eof()){item i;std::getline(file,i,',');// extract one itemnewline.push_back(i);}data.push_back(newline);//add  full line to data}infile.close();// finished with input file// at this point the data can be processedoutput(data,std::cout);//output to consolestd::fstream outfile("out.txt",std::ios::out);output(data,outfile);// output to out.txtoutfile.close();return 0;}
To me the advantage is that there are no inbuilt assumptions on size, a simple output function ensures the same format on the console and to a file and there is no explicit memory allocation or use of pointers. The data can be accessed in the same way as for an array. I know a lot of memory allocation will be done by the library but hopefully we can rely on the library to clean up by providing suitable destructors.

Statistics: Posted by RogerW — Tue Feb 06, 2024 12:25 pm



Viewing all articles
Browse latest Browse all 5284

Trending Articles