File does not open

Feb 16, 2014 at 10:05pm
Hi Guys,

When this code in compiled and executed, it should open a file, get a name and write it in the file, but it does not make the file, i dont know why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  #include<iostream>
#include<fstream>

using namespace std;

class patient
{
    char name[10];
public:
    void get_patient_info();
    const char *get_name() const;
};
void account_creation();


int main()
{
account_creation();
}
void account_creation()
{
 patient p1;
 ofstream file;
 file.open("Pateint_info.txt", ios::in);
 p1.get_patient_info();
 file.write(p1.get_name(), 10);
 file.close();
}
void patient::get_patient_info()
{
    cout<<"please enter patient name: ";
    cin.ignore();
    cin.getline(this->name, 10);
}
const char *patient::get_name() const
{
    return this->name;
}
Feb 16, 2014 at 10:13pm
You tried to force an output file stream to an input file stream? Line 23 and 24:
23
24
ofstream file;
 file.open("Pateint_info.txt", ios::in);

ifstreams will not create files if they don't exist.

There is no need to specify input or output for ofstream and ifstream.
 
ofstream file("Patient.txt");
Feb 16, 2014 at 10:21pm
OMG...you are right. i deleted ios::in and i replaced it by ios::ate to append the input to the end of the file, now it is writting some non sence staff to the file.
Feb 16, 2014 at 10:25pm
Try removing line 32. All it does there is cause you to enter input twice, the second being the patient's name.
Feb 16, 2014 at 10:31pm
But if i delete line 32, then the program does not allow me to enter the patient name.
Feb 16, 2014 at 10:40pm
I don't see where a straggling newline character might appear... But anyway, what do you mean by "nonsense stuff"?
Feb 16, 2014 at 10:45pm
ok firstly it does not append the new input to the previous input, secondly i mean for example when i write jafar as patient name, it writes this to the file: 慪慦r
Feb 16, 2014 at 10:52pm
That might be from the no longer used ios::ate flag. Try this:
 
ofstream file("Patient.txt", ios_base::app);
Feb 27, 2014 at 7:55am
Thanks man, yes it worked out.
Topic archived. No new replies allowed.