0

I have gotten to the point where the file is created and written to but it doesn't write everything to the file, or the whole line for that matter. So here is the code I have so far. A little explanation of it. I made my own functions to open and create the file then used them all in the Main function by calling them as needed. My goal is to get the file to save the Full name of the person, Age, & occupation on a separate line.( I will be added things to store as well this is what I'm starting with ). Then display it on a separate line with the while loop I am using.

#include <cmath>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// function creates and opens a new text file to add information to
    >>void CreateOpen() {
    ofstream MyFile("StudentID.txt");
    // Used to Write to the file
    string x;
    cout << "Type your Full name";
    getline (cin, x);
    string y;
    cout << "Type your Age";
    cin >> y;
    string z;
    cout << "Type your Ocupation";
    getline (cin, z);
    MyFile << x, "\n";
    MyFile << y, "\n";
    MyFile << z, "\n";
    // Close the file
    MyFile.close();
}
>void open() {
    ofstream MyReadFile("StudentID.txt");
}
int main() {
    CreateOpen();
    string g;
    cin >> g;
    cout << g;
    string myText;
    ifstream MyFile("StudentID.txt");
    while (getline( MyFile, myText )) {
        // Output the text from the file
        cout << "\n" << myText << "\n";
    }
}
Marky2019
  • 37
  • 6
  • Probably unrelated: Odds are very high that `cin >> y;` will leave a newline in the stream to mess up `getline (cin, z);`. Recommendation: give variables descriptive names. A reader should be able to look at the code and make very good assumptions about what a variable represents and how it is used from the name alone. – user4581301 Apr 19 '20 at 21:48
  • `MyFile << x, "\n";` doesn't do what you seem to expect it to do. The comma operator resolves the left side of the comma and discards the result, then keeps the result of the left.. You probably want `MyFile << x << "\n";` Might be a warning from the compiler about this. – user4581301 Apr 19 '20 at 21:50
  • Hah. First comment is not probably unrelated. It IS the bug. – user4581301 Apr 19 '20 at 21:52

0 Answers0