I replaced the gets() with scanf and this is my new program:
Code:
#include "stdio.h"
#include "conio.h"
#include "string.h"
void enter(char lib[100][3][50]);
void findAuthor(char lib[100][3][50]);
void findTitle(char lib[100][3][50]);
int main(void)
{
char choice = '1';
char catalog[100][3][50];
do {
printf("Card Catalog:\n");
printf("1. Enter\n2. Search by Author\n3. Search by Title\n4. Quit\n");
printf("Enter your choice here: ");
choice = getchar();
while(choice!='1'&&choice!='2'&&choice!='3'&&choice!='4'){
printf("\nInvalid choice. Try again.");
choice = getchar();
}
switch(choice) {
case('1'):
enter(catalog);
break;
case('2'):
findAuthor(catalog);
break;
case('3'):
findTitle(catalog);
break;
}
} while(choice!='4');
printf("Thank you for using the Library Catalog. Press any key to exit.");
getch();
return 0;
}
void enter(char lib[100][3][50])
{
int i;
char author[50];
char title[50];
char publisher[50];
for(i=0;i<101;i++){
printf("\nEnter the title: ");
scanf("%50s",author);
if(!strcmp(author,"\r")) break;
printf("\nEnter the author: ");
scanf("%50s",title);
printf("\nEnter the publisher: ");
scanf("%50s",publisher);
}
}
void findAuthor(char lib[100][3][50])
{
char author[50];
int i;
printf("Enter the author: ");
scanf("%50s",author);
for(i=0;*lib[i][1];i++){
if(!strcmp(author,lib[i][1])) {
printf("Title: %.50s\n",lib[i][2]);
printf("Publisher: %.50s\n",lib[i][3]);
break;
}
else printf("No matches found.");
}
}
void findTitle(char lib[100][3][50])
{
char title[50];
int i;
printf("Enter the title: ");
scanf("%50s",title);
for(i=0;*lib[i][1];i++){
if(!strcmp(title,lib[i][2])){
printf("Author: %.50s\n",lib[i][1]);
printf("Publisher: %.50s\n",lib[i][3]);
break;
}
else printf("No matches found.");
}
}
This program still suffers from the newline character being in the input stream when it isn't supposed to be like you mentioned, but I am not sure where to place the while loop fragment you posted.
There are two other problems. First, when the findAuthor and findTitle functions fail to find a match, the initial menu is printed out without "No matches found." being printed.
The second problem is the line
Code:
if(!strcmp(author,"\r")) break;
in the enter function. I want the loop to break when the user enters in a blank line (i.e. just presses enter). I have tried strcmp with \r and \n but neither work, so I can never exit the loop. I'm not sure what to compare it with to exit the loop, or whether using strcmp is even the right way to do it.