Posted By

somada141 on 03/12/10


Tagged

file c stream


Versions (?)

Using fstreams to write and read data #3


 / Published in: C++
 

  1. #include <fstream>
  2. #include <iostream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8.  
  9. {
  10.  
  11. int choice;//A control variable for the user's choice
  12. string FirstName, LastName; //string variables
  13. string FileName;
  14. int Age; //numeric variable
  15.  
  16. //We ask the user what he wants to do
  17. cout<<"What do you want to do?n";
  18. cout<<"(1) Write a file with your name and agen";
  19. cout<<"(2) Read from a file your name and agen";
  20. cin >> choice;
  21.  
  22. if (choice==1){
  23.  
  24. //ask the user for some input to save
  25. cout << "Enter First Name: ";
  26. cin >> FirstName;
  27. cout << "Enter Last Name: ";
  28. cin >> LastName;
  29. cout << "Enter Age: ";
  30. cin >> Age;
  31.  
  32. cout << "nEnter the name of the file you want to create: ";
  33. cin >> FileName;
  34.  
  35. /*
  36.   * Here is the important part:
  37.   *
  38.   * 1)We create a new output stream which will be used to save data into the file
  39.   * In this case the 'ofstream'constructor needs the filename and the stream type
  40.   * a)IMPORTANT: The filename path must be a C 'char' type and not a string, so we convert the string
  41.   * using the 'cstr()' function
  42.   * b)In this case we want to create an output file which will contain ASCII data hence we use
  43.   * the ios::out' modifier
  44.   *
  45.   * 2)We use the ofstream the same way we use the 'cout' stream. With the '<<' operator we throw data in
  46.   * the stream which are in turn saved into the file
  47.   * a)IMPORTANT: Note that we break the line after each variable by saving 'n'
  48.   * This is necessary here because if we don't, when reading the file the multiple variables will be considered
  49.   * as one variable.
  50.   */
  51. ofstream Students(FileName.c_str(), ios::out);
  52. Students << FirstName << "n" << LastName << "n" << Age;
  53.  
  54. }
  55. else if (choice==2){
  56.  
  57. cout << "Enter the name of the file you want to open: ";
  58. cin >> FileName;
  59.  
  60. ifstream Students(FileName.c_str());
  61. Students >> FirstName >> LastName >> Age;
  62.  
  63. cout << "nFirst Name: " << FirstName;
  64. cout << "nLast Name: " << LastName;
  65. cout << "nEnter Age: " << Age;
  66. cout << "nn";
  67.  
  68. }
  69. return 0;
  70.  
  71. }

Report this snippet  

You need to login to post a comment.