Allowing user to open and select file to read using datastreams

Hi everyone,

I am trying to code a program which will allow the user to read a .csv (or another text file) but the user must be able to choose the file to be opened. My code looks something like this for the time being, although I will be adding some getline functions:

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
#include <iostream>
#include <iomanip>
#include <string>

#include <fstream>

int main() // <--- Missing closing ).
{
	int k = 0;

	// Open Stream
	std::ifstream myFile("hello.csv");

	if (!myFile)
	{
		std::cout << "Error opening file" << std::endl;
		return 0;
	}

	// transfer data
	std::string x[2000];

	while (std::getline(myFile,x[k], ','))
	{
		std::cout << x[k++] << std::endl;
	}

	//close stream
	myFile.close();

	return 0;
}


But what I most concerned about is how to enable the user to choose the file to be read. I am using Qt and I will be coding a GUI to link the widgets onto the functions so the idea would be to have a button and for a window to pop up and allow the user to select the file but I just don't know how to do it.
To my mind, the best way to do this is to read from cin. Then the user can select a file on the command line:
myProg < myfile

or generate it on the fly from something else and pipe it into the program:
someProgram | myProg


A second option is to pass it on the command line.
1
2
3
4
5
6
7
8
9
10
int main(int argc, char **argv) {
// argc is the number of arguments (including the program name itself)
// argv elements point the arguments themselves
    if (argc < 2) {
        // print usage message, including the name of the program
        cerr << "Usage: " << argv[0] << " filename\n";
        return 1;
    }
    std::ifstream myFile(argv[1]);
    ....


A third option is to prompt the user for the file name. With code something like:
1
2
3
4
    std::string fileName;
    cout << "Enter file name: ";
    getline(cin, fileName);
    std::ifstream myFile(fileName);

I am using Qt and I will be coding a GUI to link the widgets onto the functions so the idea would be to have a button and for a window to pop up and allow the user to select the file but I just don't know how to do it.

https://lmgtfy.com/?q=QT+File+dialog&s=g
Last edited on
Topic archived. No new replies allowed.