SHARE
TWEET

Untitled

a guest Sep 22nd, 2016 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <string  >
  3. #include <fstream >
  4.  
  5.  
  6. struct User
  7. {
  8.     std::string username; // this is the problem
  9. //  char        username[50]; // this works fine
  10.     int         password;
  11.  
  12. };
  13.  
  14. int main()
  15. {
  16.     std::ofstream out("data.dat", std::ios::binary | std::ios::out | std::ios::app);
  17.     User theUser;
  18.  
  19.     std::cout << "username: ";
  20.     std::getline(std::cin, theUser.username);
  21.     std::cin.ignore(1, 'n');
  22.     std::cout << "password: ";
  23.     std::cin >> theUser.password;
  24.     std::cout << std::endl;
  25.     std::cin.ignore(1, 'n');
  26.  
  27.     out.write((char*)&theUser, sizeof(theUser));
  28.     out.flush();
  29.  
  30.  
  31.     out.close();
  32.  
  33.     std::ifstream in("data.dat", std::ios::binary | std::ios::in);
  34.  
  35.     User theUser2;
  36.  
  37.     in.seekg(0, std::ios::end);
  38.     int nUser = in.tellg() / sizeof(User);
  39.     in.clear();
  40.     in.seekg(0, std::ios::beg);
  41.  
  42.     std::cout << "nUser: " << nUser << std::endl;
  43.     std::cout << "Reading now...nn";
  44.  
  45.     for(int i(0); i < nUser; i++)
  46.     {
  47.         if(in.is_open())
  48.         {
  49.             in.read((char*)&theUser2, sizeof(User));
  50.             std::cout << "username: " << theUser2.username << std::endl;
  51.             std::cout << "password: " << theUser2.password << std::endl;
  52.         }
  53.     }
  54.  
  55.     in.close();
  56.  
  57.     std::cout << std::endl;
  58.     return 0;
  59. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top