-3

I am trying to add data in a file using fstream function of C++ but some how my one field call name is not showing inside the file as well as not in my buffer hear is the code and can you please give me some tips to debug this kind of problem. I really can't debug this kind of problem in general.

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
class student
{
    char usn[3];
    char name[10];
    char age[5];
    char buf[25];
    public:
    void pack();
    void unpack();
    void searh();
    void add();
    void dele();
}s;
void student::pack()
{
    strcpy(buf,usn);
    strcat(buf,"|");
    strcat(buf,name);
    strcat(buf,"|");
    strcat(buf,age);
    for (int i=strlen(buf);i<20;i++)
    strcat(buf,"#");
}
void student::unpack()
{
    strcpy(usn,strtok(buf,"|"));
    strcpy(name,strtok(NULL,"|"));
    strcpy(age,strtok(NULL,"#"));
}
void student::add()
{
    cout << " give student's details \n";
    cout << "name : \n";
    cin >> name;
    cout << "usn : \n";
    cin >> usn;
    cout << "age : \n";
    cin >> age;
    pack();
    fstream fout;
    fout.open("student.txt",ios::in);
    cout << buf;
    fout << buf;
}
int main()
{
    cout << "main";
    s.add();
}
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
  • 2
    The best tip on debugging that anyone can ever give you is to step through each line of the program's code, looking at how the values of variables change. Not only will that help you to understand how the code works, it will also make it painfully obvious where something is broken. (It is also best to do this *before* asking a question, so that you can ask a more specific, detailed question.) – Cody Gray - on strike May 24 '14 at 13:17
  • Well, for one, you are opening `fout` for reading (`ios::in`) instead of writing (`ios::out`). – rodrigo May 24 '14 at 13:19
  • You are mixing C and C++, this leads to very bad code. In C++, **don't** use `strcpy()` and other similar string handling functions. – kebs May 24 '14 at 13:32
  • 1
    ... unless you know how – 4pie0 May 24 '14 at 13:37

2 Answers2

1

You have opened file in read mode:

fstream fout;
fout.open("student.txt",ios::in);

so you cannot do:

fout << buf;

Instead open it with:

fout.open( "student.txt", ios::in | ios::out);

This is also a default for fstream so you can abbreviate this to:

fout.open( "student.txt");

And better not to bring whole standard namespace into scope.

4pie0
  • 29,204
  • 9
  • 82
  • 118
  • To clarify: it's OK to drag `std` into scope in a source file, [just don't do it in a header file](http://stackoverflow.com/questions/5849457/using-namespace-in-c-headers). – Mike DeSimone May 24 '14 at 13:34
0

Looks like you are opening the file you seem to want to write to in input mode - ios::in.

Also, I would allow more room in buf.

GTAE86
  • 1,780
  • 3
  • 29
  • 39