Doubt in basic file handling

I wrote this code but not able to get desired result. It runs without any errors by compiler but ends unexpectedly with partially correct and incorrect data. This code was compiled on Dev C++ and codeblocks both.
Please Help.
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
40
41
42
43
44
45
46
47
48
#include<fstream>
#include<iostream>
#include<stdio.h>

using namespace std;

class student
{
  private:
    char address[80];
  protected:
    int roll_no;
  public:
    char name[10];
    void get_data()
    {
      gets(address);
      cin.get(name,10);
      cin>>roll_no;
    }
    void show_data()
    {
      cout<<address<<endl;
      cout<<roll_no<<endl;
      cout<<name<<endl;
    }
    void write_in_file()
    {
      fstream p;
      p.open("data.txt",ios::app);
      p<<"name: "<<name<<"\t"<<"roll: "<<roll_no<<"\t"<<"address: "<<address<<endl;
      p.close();
    }
}s[2];

int main()
{
  int i = 0;
  cout<<"Enter Data"<<endl;
  for(i=0; i<2 ; i++)
  {
    cout<<i<<" student: ";
    s[i].get_data();
    s[i].write_in_file();
    cout<<endl;
  }
  return 0;
}
Last edited on
>gets(address);
https://en.cppreference.com/w/cpp/io/c/gets
Nobody should be going anywhere near this function. If your tutor told you to use this, they're an idiot.

Remove your include of stdio.h and stick to C++ iostream methods.

>cin.get(name,10);
>cin>>roll_no;

In the space of 3 lines, you used 3 separate mechanisms for inputting data.
So my guess is they're busy tripping over each others feet to give you a consistent answer.

Anyway, after >>, you should use cin.ignore() to discard data up to the next newline.
https://en.cppreference.com/w/cpp/io/basic_istream/ignore
>gets(address);
Then what statement should I use instead of this?

Is this okay?
void get_data()
{
cin.get(address,80);
cin.get(naam,10);
cin>>roll_no;
cin.ignore();
}

cause none of them is giving right output.
I am new to this topic and have no tutor.
Last edited on
Yeah, get doesn't consume the \n, but it's sufficient for get to end input.
https://en.cppreference.com/w/cpp/io/basic_istream/get

So
1
2
3
4
5
6
7
8
9
    void get_data()
    {
      cin.get(address,80);
      cin.ignore();
      cin.get(name,10);
      cin.ignore();
      cin>>roll_no;
      cin.ignore();
    }


There is a getline() method which will consume the \n as part of what it does, but you'll still need the ignore after the >> operator if you use both.
Thanks a lot.
Topic archived. No new replies allowed.