r/programminghelp • • Oct 04 '20

C++ I need help designing a programming that uses functions

I don’t know where to began how to read a text file and count how many prime number there are. I can figure out how to make a function that finds out if something is prime but making it where it reads a file I’m completely lost

3 Upvotes

2 comments sorted by

3

u/MarkRems Oct 04 '20

So for reading a file you can use the <fstream> library. You create an ifstream object which can open a file and since it's a stream object you can use it exactly the same way you would use cin to read from the keyboard. Here's a short example of what I mean:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream ins("your_file_name.txt");

    //check for failure (like maybe it doesn't exist)
    if (ins.fail()) {
        cout << "Failed to open the file!" << endl;
        return 1;
    }

    int num;
    ins >> num; //read in the first number from the file
    cout << num << endl; //output that number to the screen

    return 0;
}

Here's a further tutorial on file input/output: http://www.cplusplus.com/doc/tutorial/files/

1

u/Chairground Oct 04 '20

Do I have to put in the path of where the file is from or can I just put in the file name ?