c++ - How to get the specific output while reading from file -


#include<iostream> #include<fstream> #include<stdlib.h> #include<string.h> using namespace std; class data { public:     char name[20];     long long int ph;     data()     {         strcpy(name," ");         for(int i=0;i<10;i++)         ph=0;         }     void getdata()     {         cin>>name;         cin>>ph;         } };  int main() { int n; fstream file; file.open("test1.txt",ios::app|ios::out); if(!file) {     cout<<"file open error"<<endl;     return 0;} cout<<"number of data want enter"<<endl; cin>>n; char a[1000]; //data temp; data d[n]; for(int i=0;i<n;i++) {     d[i].getdata();     file<<d[i].name<<" ";     file<<d[i].ph<<endl;     }     file.close(); file.open("test1.txt",ios::in); file.seekg(0); file>>a; while(!file.eof()) {     cout<<a<<endl;     file>>a;     //cout<<a<<endl;     } cout<<"enter index"<<endl; int in; cin>>in; int pos=(in-1)*(sizeof(d[0])); file.seekg(pos);         file>>a;     //cout<<a<<endl;     file.read((char *)(&d[pos]),sizeof(d[0]));     cout<<a<<endl;     file.close();     system("pause");     return 0; } 

if entering following data:
number of data want enter
2
abc 88
xyz 99
enter index:
2
xyz 99 //i need output.
99// getting output
99
code not reading char array present in file.

too complex, i'm presenting simpler solution.

class data {   public:       data (const std::string& new_name = "",           long long int new_ph = 0ll)     : name(new_name), ph(new_ph) // initialization list     { ; }      friend std::istream& operator>>(std::istream& inp,                                     data& d);     friend std::ostream& operator<<(std::ostream& out,                                     const data& d);   private:      std::string name;      long long int ph; // recommend string phone numbers };  std::istream& operator>>(std::istream& inp,                          data& d) {   inp >> d.name;   inp >> d.ph;   return inp; }  std::ostream& operator>>(std::ostream& out,                          const data& d) {   out << d.name << ' ' << d.ph << "\n";   return out; }  // ... std::vector<data> my_vector; input_file >> quantity; input_file.ignore(10000, '\n'); data d; while (input_file >> d) {   my_vector.push_back(d); } (unsigned int = 0; < my_vector.size(); ++i) {   cout << my_vector[i]; } //...   

i have overloaded operator>> read in data item , overloaded operator<< output data item.

and look, no use of char[] name. no worries memory allocation or name overflows.

the input works files , console input, without changes!


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -