c++ get array string from text file -


my text file like

jason derulo 91 western road,xxxx,xxxx 1000 david beckham 91 western road,xxxx,xxxx 1000 

i'm trying data text file , save arrays when want store data text file array loop non-stop. should ? problem exiting in looping or method data text file ?

code:

#include <iostream> #include <fstream>  using namespace std;  typedef struct {      char name[30];     char address[50];     double balance;  } account;  //function prototype void menu(); void read_data(account record[]);  int main() {     account record[31]; //define array 'record'  have maximum size of 30     read_data(record);   } //--------------------------------------------------------------------  void read_data(account record[]) {     ifstream openfile("list.txt");              //open text file       if (!openfile) {         cout << "error opening input file\n";         return 0;     } else {         int loop = -1;                  //size of array          cout << "--------------data file--------------"<<endl;         while (!openfile.eof())  {         if (openfile.peek() == '\n')              openfile.ignore(256, '\n');         openfile.getline(record[loop].name, 30);         openfile.getline(record[loop].address, 50);         openfile >> record[loop].balance;         }         openfile.close();               //close text file          (int = 0; <= loop + 1; i++) {             cout << "account "  << endl;             cout << "name         : " << record[i].name << endl;             cout << "address      : " << record[i].address << endl;             cout << "balance      : " << record[i].balance << endl;         }     } } 

use ifstream::getline() instead of ifstream::eof() in tandem >>. following illustrative example, (and simplicity didn't check see if stream opened correctly).

#include <iostream> #include <fstream> #include <string> using namespace std;  #define arr_size 31  typedef struct {     char name[30];     char address[50];     double balance; } account;  int main() {   account temp, record[arr_size];   ifstream ifile("list.txt");   int i=0;   double d=0;    while(i < arr_size) {     ifile.getline(temp.name, 30, '\n');//use size of array     ifile.getline(temp.address, 50, '\n');//same here      //consume newline still in stream:         if((ifile >> d).get()) { temp.balance = d; }      record[i] = temp;     i++;   }    (int i=0; < arr_size; i++) {     cout << record[i].name << "\n"           << record[i].address << "\n"           << record[i].balance << "\n\n";   }   return 0; } 

another recommendation use vectors record array, , strings instead of char arrays.

references:

why std::getline() skip input after formatted extraction?


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -