file not displaying

closed account (1vf9z8AR)
Inputs values but doesnt display them

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
    int rno;
    fstream f1("text.txt",ios::out|ios::binary);
    f1.open("text.txt");
        cout<<"Enter roll number";cin>>rno;cout<<endl;
    f1<<rno;
    f1.close();
    
    string line;
      fstream r1("text.txt",ios::in|ios::binary);
      r1.open("text.txt");
      while(r1>>line)
    {
    cout<<line<<endl;
    }
    return 0;
}
closed account (1vf9z8AR)
similar program but infinite output

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
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
    int rno;
    fstream f1("text.txt",ios::out|ios::binary);
    f1.open("text.txt");
        cout<<"Enter roll number";cin>>rno;cout<<endl;
    f1<<rno;
    f1.close();

    string line;
      fstream r1("text.txt",ios::in|ios::binary);
      r1.open("text.txt");
      while(!r1.eof())
    {
        r1>>rno;
    cout<<rno<<endl;
    }
    r1.close();
    return 0;
}
After opening a file you should check that it is open before you use it.
Also it's easier if you open the file in text mode than binary.
If you write an int to the file it's easier to read an int back.
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
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib> // perror

using namespace std;

int main()
{
  int rno;
  fstream f1("text.txt", ios::out);
  if (!f1)
  {
    perror(nullptr);
    return -1;
  }
  cout << "Enter roll number: "; 
  cin >> rno; 
  cout << endl;
  f1 << rno;
  f1.close();

  int num;
  fstream r1("text.txt", ios::in);
  if (!r1)
  {
    perror(nullptr);
    return -1;
  }
  while (r1 >> num)
  {
    cout << "Number read: " << num << endl;
  }
  return 0;
}
Topic archived. No new replies allowed.