Problemas com lógica - volta ao menu inicial de função int main()

1. Problemas com lógica - volta ao menu inicial de função int main()

Paulo Pimenta
paulopimenta6

(usa Debian)

Enviado em 17/02/2024 - 17:45h

Olá pessoal,

Comecei a fazer um código de um sistema de cadastro, mas tive problema, pois o mesmo não retorna ao menu principal. Como existe uma interação entre máquina e usuário continuamente preciso limpar o buffer, porém o mesmo parece atrapalhar na hora que eu tento voltar ou executar uma opção após o primeiro cadastro.

Seguem os códigos:
app.cpp:
 #include <iostream>
#include <string>
#include <ncurses.h>
#include <limits>
#include "book.h"

void addBook(int& counter);
void deleteBook(int& counter);
void editBook(int& counter);
void searchBook(int counter);
void viewAllBooks(int counter);
void quit();

const int MAX_BOOKS = 4;
bool flag = true;

void increment(int& counter) { counter++; }
void decrement(int& counter) { counter--; }

bookLib::Book books[MAX_BOOKS];

int main() {
int counter = 0;
int ans;

initscr(); // Inicializa a tela do ncurses
raw(); // Desabilita buffering de linha
keypad(stdscr, TRUE); // Habilita leitura de teclas especiais

while (flag) {
clear(); // Limpa a tela

printw("LIBRARY MANAGEMENT SYSTEM\n\n");
printw("[1]ADD BOOK\n");
printw("[2]DELETE BOOK\n");
printw("[3]EDIT BOOK\n");
printw("[4]SEARCH BOOK\n");
printw("[5]VIEW ALL BOOKS\n");
printw("[6]QUIT\n\n");

printw("ENTER CHOICE: ");
refresh(); // Atualiza a tela

scanw("%d", &ans);

switch (ans) {
case 1:
addBook(counter);
break;
case 2:
deleteBook(counter);
break;
case 3:
editBook(counter);
break;
case 4:
searchBook(counter);
break;
case 5:
viewAllBooks(counter);
break;
case 6:
quit();
break;
default:
printw("Invalid option! Try again\n");
refresh();
}

getch(); // Espera por um caractere
}

endwin(); // Finaliza a tela do ncurses
return 0;
}

void addBook(int& counter) {
std::string isbn, title, author, edition, publication;

if (counter >= MAX_BOOKS) {
printw("YOU HAVE REACHED THE MAXIMUM NUMBER OF BOOKS TO BE ADDED!\n\nPress any key to continue . . .");
getch();
return;
}

printw("ADDING BOOK...\n");
printw("Enter ISBN: ");
refresh();

// Ler o ISBN usando getch()
char isbnBuffer[20];
getstr(isbnBuffer);
isbn = isbnBuffer;

// Verificar se o ISBN já existe
for (int i = 0; i < counter; i++) {
if (books[i].getIsbn() == isbn) {
printw("ISBN already exists. Please enter a different ISBN.\n");
getch();
return;
}
}

printw("Enter Title: ");
refresh();
char titleBuffer[100];
getstr(titleBuffer);
title = titleBuffer;

printw("Enter Author: ");
refresh();
char authorBuffer[100];
getstr(authorBuffer);
author = authorBuffer;

printw("Enter Edition: ");
refresh();
char editionBuffer[100];
getstr(editionBuffer);
edition = editionBuffer;

printw("Enter Publication: ");
refresh();
char publicationBuffer[100];
getstr(publicationBuffer);
publication = publicationBuffer;

books[counter].setIsbn(isbn);
books[counter].setTitle(title);
books[counter].setAuthor(author);
books[counter].setEdition(edition);
books[counter].setPublication(publication);

increment(counter);
printw("\nBOOK ADDED SUCCESSFULLY!\n\nPress any key to continue . . .");
getch();
}

void deleteBook(int& counter) {
std::string isbn;
int choice;
bool bookFound = false;

if (counter == 0) {
printw("THERE IS NO BOOK TO DELETE!\n\nPress any key to continue . . .");
getch();
return;
}

printw("DELETE BOOK\n\n");
printw("Enter ISBN: ");
refresh();

char isbnBuffer[20];
getstr(isbnBuffer);
isbn = isbnBuffer;

for (int i = 0; i < counter; i++) {
if (books[i].getIsbn() == isbn) {
printw("\nBOOK FOUND\n\n");
printw("Do you want to delete?\n[1] Yes\n[2] No\n\nEnter Choice: ");
refresh();
std::cin >> choice;

if (choice == 1) {
for (int a = i; a < counter - 1; a++) {
books[a] = books[a + 1];
}
counter--;
books[counter].setIsbn("");
books[counter].setTitle("");
books[counter].setAuthor("");
books[counter].setEdition("");
books[counter].setPublication("");
printw("\nBOOK SUCCESSFULLY DELETED!\n\nPress any key to continue . . .");
getch();
}

bookFound = true;
break;
}
}

if (!bookFound) {
printw("\nBOOK NOT FOUND!\n\nPress any key to continue . . .");
getch();
}

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
}

void editBook(int& counter) {
std::string editIsbn, choice;
std::string isbn, title, author, edition, publication;
bool editBookFound = false;

printw("\nEDIT BOOK\n\n");

if (counter == 0) {
printw("THERE IS NO BOOK TO EDIT!\n\nPress any key to continue . . .");
getch();
return;
}

printw("Enter ISBN: ");
//refresh();
std::cin.ignore();
std::getline(std::cin, editIsbn);

for (int i = 0; i < counter; i++) {
if (books[i].getIsbn() == editIsbn) {
printw("\nBOOK FOUND!\n\n");
printw("\nDo you want to edit?\n[1] Yes\n[2] No\n\nEnter choice: ");
refresh();
std::getline(std::cin, choice);

if (choice == "1") {
printw("Enter ISBN: ");
refresh();
std::getline(std::cin, isbn);
printw("Enter Title: ");
refresh();
std::getline(std::cin, title);
printw("Enter Author: ");
refresh();
std::getline(std::cin, author);
printw("Enter Edition: ");
refresh();
std::getline(std::cin, edition);
printw("Enter Publication: ");
refresh();
std::getline(std::cin, publication);
books[i].setIsbn(isbn);
books[i].setTitle(title);
books[i].setAuthor(author);
books[i].setEdition(edition);
books[i].setPublication(publication);
printw("\nBOOK EDITED SUCCESSFULLY!\n\nPress any key to continue . . .");
getch();
}

editBookFound = true;
break;
}
}

if (!editBookFound) {
printw("\nBOOK NOT FOUND!\n\nPress any key to continue . . .");
getch();
}
}

void searchBook(int counter) {
std::string isbn;
bool print = false;

printw("SEARCH BOOK\n\n");
if (counter == 0) {
printw("THERE IS NO BOOK TO SEARCH!\n\nPress any key to continue . . .");
getch();
return;
}

printw("Enter ISBN: ");
refresh();
std::getline(std::cin, isbn);

for (int i = 0; i < counter; i++) {
if (books[i].getIsbn() == isbn) {
printw("\nBOOK FOUND!\n\n");
printw("ISBN: %s\n", books[i].getIsbn().c_str());
printw("TITLE: %s\n", books[i].getTitle().c_str());
printw("AUTHOR: %s\n", books[i].getAuthor().c_str());
printw("EDITION: %s\n", books[i].getEdition().c_str());
printw("PUBLICATION: %s\n", books[i].getPublication().c_str());
printw("\n\nPress any key to continue . . .");
print = true;
}
}
if (!print) {
printw("\nBOOK NOT FOUND!\n\nPress any key to continue . . .");
}
getch();
}

void viewAllBooks(int counter) {
if (counter == 0) {
printw("THERE IS NO BOOK TO SHOW!\n\nPress any key to continue . . .");
getch();
return;
}

printw("VIEW ALL BOOKS\n\n");
for (int i = 0; i < counter; i++) {
printw("BOOK DETAILS\n\n");
printw("ISBN: %s\n", books[i].getIsbn().c_str());
printw("TITLE: %s\n", books[i].getTitle().c_str());
printw("AUTHOR: %s\n", books[i].getAuthor().c_str());
printw("EDITION: %s\n", books[i].getEdition().c_str());
printw("PUBLICATION: %s\n", books[i].getPublication().c_str());
}
printw("Press any key to continue . . .");
getch();
}

void quit() {
flag = false;
}


book.cpp:

#include<string>
#include "book.h"

using namespace std;

bookLib::Book::Book(){
this->isbn = "";
this->title = "";
this->author = "";
this->edition = "";
this->publication = "";
}

bookLib::Book::Book(string isbn, string title, string author, string edition, string publication){
this->isbn = isbn;
this->title = title;
this->author = author;
this->edition = edition;
this->publication = publication;
}

//setters
void bookLib::Book::setIsbn(string a){
this->isbn = a;
}
void bookLib::Book::setTitle(string b){
this->title = b;
}
void bookLib::Book::setAuthor(string c){
this->author = c;
}
void bookLib::Book::setEdition(string d){
this->edition = d;
}
void bookLib::Book::setPublication(string e){
this->publication = e;
}
//setters
string bookLib::Book::getIsbn(){
return this->isbn;
}
string bookLib::Book::getTitle(){
return title;
}
string bookLib::Book::getAuthor(){
return this->author;
}
string bookLib::Book::getEdition(){
return this->edition;
}
string bookLib::Book::getPublication(){
return this->publication;
}


e book.h:
#ifndef BOOK_H
#define BOOK_H

#include <string>

namespace bookLib {
class Book {
private:
std::string isbn;
std::string title;
std::string author;
std::string edition;
std::string publication;
public:
//contructor
Book();
Book(std::string, std::string, std::string, std::string, std::string);
//setters - assigning user value to private variables
void setIsbn(std::string);
void setTitle(std::string);
void setAuthor(std::string);
void setEdition(std::string);
void setPublication(std::string);
//getters - getting the values from private variables
std::string getIsbn();
std::string getTitle();
std::string getAuthor();
std::string getEdition();
std::string getPublication();
};
}

#endif


Caso vejam algumas melhorias eu ficarei bastante feliz coma ajuda!

Desde já agradeço a todos!


  


2. Re: Problemas com lógica - volta ao menu inicial de função int main()

Samuel Leonardo
SamL

(usa XUbuntu)

Enviado em 18/02/2024 - 01:41h

Use uma função simples para limpar o buffer de entrada:

void clear_stdin() {
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
}

https://stackoverflow.com/questions/7898215/how-can-i-clear-an-input-buffer-in-c

clear_stdin() vc deve usar toda vez que ler da entrada (do stdin), ou seja, quando usar getch(), então usa depois o clear_stdin, se usar scanw, faz depois uma chamada para clear_stdin, etc.

https://nerdki.blogspot.com/ acessa ai, blog dedicado Paranóia!







Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts