C++: Store contents of text file into 2D array as strings (trouble with null terminator?) -
i'm working bit more arrays , reading files try , deeper understanding of them, apologize if ask lot of questions in regards that.
i have program supposed read characters file , store characters strings 2d array. example, file contains header number , list of names:
5 billy joe sally sarah jeff
so 2d array in case have 5 rows , x number of columns (one row per names). program reads file 1 char @ time. think i'm having problem inserting null terminator @ end of each row indicate it's end of string, overall, i'm not sure what's going wrong. here code:
#include <iostream> #include <fstream> #include <string> #include <cstdlib> using namespace std; const int max_name_length = 50; void printnames(char [][max_name_length + 1], int); int main(void) { ifstream inputfile; string filename; int headernum, = 0, j; const int max_names = 10; char ch; char names[1][max_name_length + 1]; cout << "please enter name of input file: "; cin >> filename; inputfile.open(filename.c_str()); if (inputfile.fail()) { cout << "input file not opened. try again." << endl; } inputfile >> headernum; if (headernum > max_names) { cout << "maximum number of names cannot exceed " << max_names << ". please try again." << endl; exit(0); } inputfile.get(ch); while (!inputfile.eof()) { (i = 0; < headernum; i++) { (j = 0; j < max_name_length; j++) { if (ch == ' ' || ch == '\n') { names[i][j] = '\0'; } else { names[i][j] = ch; } } } inputfile.get(ch); } cout << names[0] << endl; //printnames(names, headernum); return 0; } void printnames(char fnames[][max_name_length + 1], int fheadernum) { int i; (i = 0; < fheadernum; i++) { cout << fnames[i] << endl; } }
it compiles, , here output: http://puu.sh/7pyxv.png
so wrong here! i'm incline specific problem lies if (ch = ' ' etc) statement, more that, i'm sure. i'm having trouble figuring out problem lies. always, and/or guidance appreciated!
now have feedback on initial code. here simpler way of doing (and bit more c++ like):
#include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc, char **argv) { ifstream inputfile; string filename; cout << "please enter name of input file: "; cin >> filename; inputfile.open(filename.c_str()); if (inputfile.fail()) { cout << "input file not opened. try again." << endl; return 1; } int headernum = 0; inputfile >> headernum; if(inputfile.eof()) { cout << "error reading input file contents." << endl; return 1; } string *names = new string[headernum]; for(int = 0; < headernum; i++) inputfile >> names[i]; for(int = 0; < headernum; i++) cout << names[i] << endl; }
Comments
Post a Comment