Answer to Question #103153 in C++ for mustafaa

Question #103153
Use file operations (fopen, fgets, fprintf, feof, fclose) to create a simple to-do list.

Users can add new items, print the list, and erase the entire list (but may not erase individual items)

To-do items are stored in a file, one per line.

Example I/O:


Welcome to the To-Do List.
1) Print the list
2) Add to the list
3) Erase the list
4) Exit

What would you like to do? 2
What would you like add? Buy Apples
What would you like to do? 1
Your list:
Buy Apples
What would you like to do? 3
What would you like to do? 1
Your list:
What would you like to do? 4
1
Expert's answer
2020-02-16T14:47:20-0500

#include <list>

#include <stdio.h>


using namespace std;


int main()

{

    list<char *> toDo;

    int command;

    FILE *f = fopen("toDoList", "r");

    if (f == NULL)

    {

        fclose(fopen("toDoList", "w"));

        f = fopen("toDoList", "r");

    }

    char *toAdd;

    while (!feof(f))

    {

        toAdd = new char[256];

        fgets(toAdd, 256, f);

        if (!feof(f))

            toDo.push_back(toAdd);

    }

    fclose(f);

    printf("Welcome to the To-Do List.\n1) Print the list\n");

    printf("2) Add to the list\n3) Erase the list\n4) Exit\n");

    while (true)

    {

        printf("What would you like to do? ");

        scanf("%d", &command);

        if (command == 1)

        {

            printf("Your list:\n");

            for (auto i = toDo.begin(); i != toDo.end(); i++)

                printf("%s", *i);

        }

        if (command == 2)

        {

            printf("What would you like add? ");

            toAdd = new char[256];

            fflush(stdin);

            fgets(toAdd, 257, stdin);

            toDo.push_back(toAdd);

        }

        if (command == 3)

        {

            for (auto i = toDo.begin(); i != toDo.end(); i++)

                delete [](*i);

            toDo.clear();

        }

        if (command == 4)

            break;

    }

    f = fopen("ToDoList", "w");

    for (auto i = toDo.begin(); i != toDo.end(); i++)

    {

        fputs(*i, f);

        delete []*i;

    }

    fclose(f);

    return 0;

}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS