-2

I have a problem because this is my first time encountering some functions from C that I need to convert into C++.

Code:

FILE *pokf;
char name[10],gender;
int age, i, n, b1=0, b2=0;
float p;

pokf=fopen("Data.txt","r");       
while (feof(pokf)==0) {
fscanf (pokf,"%s %c %d %f", &name, &gender, &age, &p);
if (gender=='Z') b1++;
if (p>=4.50 ) b2++;  }
fclose(pokf);

I can write:

ifstream input;
input.open("Data.txt");

But then I don't know what to use instead of pokf because I can't use FILE *pokf anymore. What to use instead of functions feof and fscanf?

  • 5
    I recommend investing in [a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). They should have all the information you need for this (and more). – Some programmer dude May 10 '20 at 13:42
  • 4
    The C code is low quality, written by someone who doesn't really know what they're doing. – john May 10 '20 at 13:46
  • 2
    It's not clear what you really want here. The title question is incredibly broad, but you seem actually to want something very much more specific. But if it's just a question of how to use C++ stream classes then I am confident that you would be better served by looking up one of the many tutorials on that topic around the web, or even by reading the classes' documentation. – John Bollinger May 10 '20 at 14:05

2 Answers2

1

The rough equivalent of fscanf is operator>> and I wouldn't worry about feof since it's being used incorrectly. So

while (feof(pokf)==0) {
    fscanf (pokf,"%s %c %d %f", &name, &gender, &age, &p);
    ...

becomes

while (pokf >> name >> gender >> age >> p) {
    ...

Although using char name[10] in C++ will work, it has the obvious problem that you are limited to names of 9 characters of less. In C++ you should use std::string instead of a char array.

john
  • 85,011
  • 4
  • 57
  • 81
0

You should be able to use FILE *pokf in c++, here is an example http://www.cplusplus.com/reference/cstdio/feof/ where you can see how to open files in c++

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}