string - Reading in numbers and names using getline in C++? -
so i've been working on problem hours , help. have program due tomorrow. basically, have input file has first , last name , 4 float numbers following. looks this:
john w. smith 78.8 56.5 34.5 23.3 jane doe 34.5 23.4 35.7 87.0 no more
i need read first , last names array of pointers. far trying read in each line variable "name" , i'm outputting text file see if have been reading in data correctly. unfortunately, stops after reads in floats, doesn't read in next names.
char *newptr; char *namelist[50] = {0}; char name[15]; int = 0; infile.getline(name, 15); while (strcmp (name, "no") != 0) { newptr = new char[15]; strcpy(newptr, name); namelist[i] = newptr; infile.getline(name, 15); outfile << name << endl; i++; }
so far, output has been:
john w.
smith
78.8 56.5 34.5 23.3
edit: loop infinite, output, know haven't processed second names yet, stop @ first numbers.
if help, great! limited functions can use, should using getline function here, cannot use fancy.
in slides, teacher has code here reading in names:
char *newptr; char *namelist[6] = {0}; char name[20]; int = 0; infile.getline(name, 20); while(strcmp(name, sentinel) != 0) { newptr = new char[20]; strcpy(newptr,name); namelist[a++] = newptr; infile.getline(name,20); }
we have not been taught strings yet , cannot use have not talked in class. thank far has commented.
you're there... main thing forgot attempt read numbers. code below reads them w
, x
, y
, z
ignores them... should whatever need them, e.g. create second array surnames , either third 2-dimensional array floats or 1-dimensional array 4 times long....
char *namelist[50] = {0}; char name[15]; int = 0; while (infile.getline(name, sizeof name) && strcmp(name, "no") != 0) { char* newptr = new char[sizeof name]; strcpy(newptr, name); namelist[i] = newptr; double w, x, y, z; if (infile.getline(name, sizeof name) && infile >> w >> x >> y >> z) outfile << name << endl; else { std::cerr << "missing rest of data " << namelist[i] << " found\n"; exit(exit_failure) } i++; }
Comments
Post a Comment