Looping menu with external file input not working

Dec 5, 2021 at 11:29pm
Hello everyone, so I'm attempting to make a file to keep important activities and dates, however, I cannot get my menu to loop back after the file is displayed. This is my first post and I'm trying to follow the guidelines as best as I can, if I have done anything wrong please correct me. I can not tell if it is a problem with my main function or my readFile.

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
void readFile()//this is my read file/ display info.
{

    ifstream HomeWorknInfo;
    HomeWorknInfo.open("dates.txt",ios::in);
    if(!HomeWorknInfo.is_open())
    {
        exit(EXIT_FAILURE);
    }
    if(HomeWorknInfo.is_open())
    {
        string line;
        while(getline(HomeWorknInfo,line))
            cout << line <<"\n";
        
    }
    HomeWorknInfo.close();

}


int main()//my main with the switch function
{
    unsigned short menuChoice=0;

    do
    {
        getMenu();
        cin >> menuChoice;
        switch(menuChoice)
        {
            case DisplayFile:
                readFile();
                break;

            case AddToFile:
                addToFile();
                break;

            case Exit:
                return 0;
            default:
                cout << "You have entered an invalid menu choice.\n"
                     <<"Please try again";
                getMenu();

        }
        //menuChoice=0;
    }while (menuChoice != Exit);
    return 0;
}
Dec 6, 2021 at 5:04am
A couple of minor points.
L10: There is no reason to call is_open() a second time. You could use an else, but really there is no need for the second if statement at all.
L28,45: If menuChoice is invalid, you're going to call getMenu() twice. Remove line 45.

Other than those two minor points, I don't see anything wrong with your code.
Have you stepped through your code with a debugger?
Dec 6, 2021 at 9:55am
You don't need L17 as the file destructor closes the file. readFile() can just be:

1
2
3
4
5
6
7
8
9
10
void readFile()
{
	ifstream HomeWorknInfo("dates.txt");

	if (!HomeWorknInfo)
		exit(EXIT_FAILURE);

	for (string line; getline(HomeWorknInfo, line); )
		cout << line << '\n';
}


I would replace L41 with just break; so that the while loop is exited normally and any post exitr code can be after the while.
Dec 6, 2021 at 10:04am
I cannot get my menu to loop back after the file is displayed.
What does it do instead?

There seems nothing wrong with readFile(). So it is most likely somewhere else.
Dec 6, 2021 at 10:37pm
@AbstractionAnon I'm pretty new to coding and I've been trying to figure out how to use the debugger, ill definitely give this a try! Thank you.
Topic archived. No new replies allowed.