prompt the user input and output filename

Hello there, I need to
prompt the user for the name of an input file and the name of an output file.

•I Make sure to verify that the input file exists,
•Use a loop to validate and get another name.
•I do not have to verify that the output file exists


what I got so far, but not with promoting
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
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>

#define SPEEDOFLIGHT 299792.46

using namespace std;

int main()
{

    //reading from a file

    ifstream infile;

    ofstream outfile;

    int lambda;
    string color;

    infile.open("myfile.txt");

    outfile.open("results.txt");

    if (!infile.is_open()&&!outfile.is_open()) 
        cout << "File not found" << endl;

    else


    {

        infile >> lambda;

        while (!infile.eof())

        {
            //calculating

            double freqency = (SPEEDOFLIGHT*1000)/lambda*(0.000000001);

            infile >> color;

            outfile << color << " "<<freqency<<" per sec.\n\n";
            //print
            cout << "The wavelength of " << color << " is "

                 << lambda << " nanometers" << endl;

            infile >> lambda;
        }
        // closing
        infile.close();
        outfile.close();
    }
    return 0;
}
Last edited on
I need to
prompt the user for the name of an input file and the name of an output file.

•I Make sure to verify that the input file exists,
•Use a loop to validate and get another name.
•I do not have to verify that the output file exists


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <fstream>
#include <iostream>
#include <string>
#include <filesystem>

int main()
{
	std::string ifn, ofn;

	do {
		std::cout << "Enter input file name: ";
		std::getline(std::cin, ifn);

		if (!ifn.empty()) {
			std::cout << "Enter output file name: ";
			std::getline(std::cin, ofn);

			std::cout << ifn << (std::filesystem::exists(ifn) ? " exists" : " does not exist") << '\n';
		}
	} while (!ifn.empty());
}

And in case you can't get <filesystem> working, note that:
if (!infile.is_open()&&!outfile.is_open()) is not what the requirement is.

An outfile not opening successfully means that the outfile was not created, which is either a matter of permissions, OS restrictions, or hard-drive space.

Your requirement says to check if the input file exists, and in this case it's good enough to just check if it's opened successfully, because that's what really matters.

In other words, your condition here could just be:
1
2
if (!infile.is_open()) 
        cout << "Input file not found" << endl;
Last edited on
thanks everyone I got it
Topic archived. No new replies allowed.