In my program there is a minor problem.
When I press 2 or 3 or 4 it will display the properly but after that when I
press the a or b or c etc., it will display previous one result instead of print the Invalid option.
How can I fix this?
#include <stdio.h>
#include <string.h>
typedef struct vehicle
{
char name[100];
char lice_no[25];
int vehicle_type;
char cmpny_name[100];
int menu_year;
}record;
int main(void)
{
int i,choice;
FILE *fp1,*fp2;
char oname[100];
record det,det1;
int recsize;
char c;
fp1 = fopen("record.dat" , "r+");
if(fp1 == NULL)
{
fp1 = fopen("record.dat" , "w+");
if(fp1 == NULL)
{
printf("error in opening file : \n");
return -1;
}
}
recsize = sizeof(det);
do
{
printf("\t\"enter the choice\"\n");
printf("1 : adding the record\n");
printf("2 : delete the record\n");
printf("3 : editing the record\n");
printf("4 : display the record\n");
printf("5 : exit the program\n");
fflush(stdin);
scanf("%d" , &choice);
scanf("%c" , &c);
switch(choice)
{
case 1 :
{
printf("In this add logic\n")
break;
}
case 2 :
{
printf("In this case delete logic\n");
break;
}
case 3 :
{
printf("In this case edit logic\n");
break;
}
case 4 :
{
printf("display logic\n");
break;
}
case 5 :
{
printf("exit logic\n");
break;
}
default :
{
printf("\"Invalid option\"\n");
break;
}
}
}
while(1);
return 0;
}
It looks like you are getting the numbers into Choice, and the chars into c.
but you are only using the Choice var in the switch, you are never checking the C var.
So essentially, if you hit a letter it is storing it in the C var, and then using the old value in Choice again.
Hmm, one of the things wrong in your codes is the:
scanf("%c" , &c);
because, the scanf function requires the user to press the enter key before it could store the character to its respective variable.
So if the compiler reads the line:
scanf("%c" , &c);
it reads your input, PLUS, the ENTER.
Thus forcing the scanf function to store your input, PLUS, the ENTER, into your character variable.
It would be better if you would use getche() or getch() instead of using scanf() function, and please do not ever use:
scanf("%c" , &c);
because it would generate an error.
Sample of usage of getche() or getch() function:
c=getche(); //waits for a keypress and stores it on a variable
c=getch(); //waits for a keypress and stores it on a variable
the difference between the two is that the getche() displays your keypress while the getch() does not.
Note: Do not forget to put
#include<conio.h>
Added info:
If you still want to go on using the scanf() function just make sure that you declare your favorite variable as:
char c[20];
then you may use:
scanf("%s", &c);
but your variable, can only hold up to 19 characters, as how we declared on your character array.
And the summary is do not use:
scanf("%c", &c);
because, it can affect your other scanf() functions. :)
SOLUTION(Spoiler Warning):
#include <stdio.h>
#include <string.h>
#include <conio.h>
typedef struct vehicle
{
char name[100];
char lice_no[25];
int vehicle_type;
char cmpny_name[100];
int menu_year;
}record;
int main(void)
{
int i; //removed choice from int
FILE *fp1,*fp2;
char oname[100];
record det,det1;
char choice; //made the variable choice a character
int recsize;
char c;
fp1 = fopen("record.dat" , "r+");
if(fp1 == NULL)
{
fp1 = fopen("record.dat" , "w+");
if(fp1 == NULL)
{
printf("error in opening file : \n");
return -1;
}
}
recsize = sizeof(det);
do
{
printf("\t\"enter the choice\"\n");
printf("1 : adding the record\n");
printf("2 : delete the record\n");
printf("3 : editing the record\n");
printf("4 : display the record\n");
printf("5 : exit the program\n");
fflush(stdin);
choice = getche(); // or getch()
switch(choice) //changed the target character
{
case '1' : //changed the case from 1 to '1'
{
printf("In this add logic\n");
break;
}
case '2' : //changed the case from 2 to '2'
{
printf("In this case delete logic\n");
break;
}
case '3' : //changed the case from 3 to '3'
{
printf("In this case edit logic\n");
break;
}
case '4' : //changed the case from 4 to '4'
{
printf("display logic\n");
break;
}
case '5' : //changed the case from 5 to '5'
{
printf("exit logic\n");
break;
}
default :
{
printf("\"Invalid option\"\n");
break;
}
}
}
while(1);
return 0;
}
You can also use switch to compare characters. Just change the values
case 1:
to
case '1':
scanf returns you a value, which you don't check.
When used with %d specifier - it should parse an integer. Since you enter a non-integer value - scanf returns you an error code, and choice is unchanged
It's because in c when you are reading characters as integers (scanf("%d" , &choice);) it takes the ascii code of the characters for example a = 97, b = 98 c = 99 d = 100 if you want to read a as 1 b as 2 etc you will have to add some extra code that tells the programme if the number is equal to the ascii code of a b c d or e subtract it with 96 so you get 1,2,3..
Related
I have a file student.txt and it has a content like
Name RollNo Address ...\n
Name RollNo Address ...\n
And I have written a function to search a Name in the file
it's menu driven and goes like
std student;
FILE *file = NULL;
int choice;
char name[20];
while (1)
{
printf("Enter the choice\n1.Insert\t2.Append\t3.Search\t4.Display: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
//insertion
break;
case 2:
// append
break;
case 3:
printf("Enter the student name to be searched: ");
scanf("%d", &name);
search(name, &file);
break;
case 4:
// display
break;
default:
exit(0);
break;
}
}
return 0;
search function is
void search(char ele[], FILE **fileptr)
{
*fileptr = freopen("student.txt", "r", *fileptr);
char line[100];
while (fgets(line, 100, *fileptr) != NULL)
{
if (strstr(line, ele) != NULL)
{
getchar();
printf("Congrats !!\n");
return;
}
}
printf("not found\n");
fclose(*fileptr);
}
But when i run this though has a filename matching filename it goes to an infinite loop and executes display function and triggers search function itself infinitely
It happens when the data is not taken in correctly using a correct format specifier.
In case 3, in the scanf function, use the format specifier
%s
instead of
%d
That will stop the infinite loop.
---------- > ## Heading ## > when i input a character as an input default case of switch doesn't encounter and loop started > infinite times > > > enter code here
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void create();
void display();
void search();
struct node {
int data;
struct node* link;
};
struct node* head;
int main()
{
int value;
while (1) {
printf("Enter Correct Choice :- \n");
printf("Enter 1 to Create Linklist :- \n");
printf("Enter 2 to Display Linklist :- \n");
printf("Enter 3 to Search Linklist :- \n");
printf("Enter Your Choice Here _________ ");
scanf(" %d", &value);
switch (value) {
case 1:
create();
break;
case 2:
display();
break;
case 3:
search();
break;
default:
printf("Error !! Wrong Choice :- \n");
break;
}
}
return 0;
}
TL;DR- Always check the return value of scanf() for success.
In case of a non-numeric character input, the format specifier %d does not find a match, and no input is consumed (i.e., the invalid input remains in the input buffer). Thus, the switch body executes, most likely it does not find a match with any existing case statement, so the default case statement(s) get executed, and control goes back to while loop.
Then, due to the presence of the invalid input in the buffer (and not getting consumed), the above phenomena keeps on repeating.
The major problem is, in case of scanf() failure, the value of variable value remains uninitialized and indeterminate. It does not construct a well-defined program.
Couple of things:
Always initialize local variables.
Always check for success of scanf() before using the returned value, if you have to use scanf(). For better use fgets() to take user input.
In case of failure of input using scanf(), clean up the input buffer before trying to read next input.
The break causes the program to exit the switch case but not the while. To wxit the while as well you should do something like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int value;
int done = 0;
while (!done) {
printf("Enter Correct Choice :- \n");
printf("Enter 1 to Create Linklist :- \n");
printf("Enter 2 to Display Linklist :- \n");
printf("Enter 3 to Search Linklist :- \n");
printf("Enter Your Choice Here _________ ");
scanf(" %d", &value);
switch (value) {
case 1:
printf("do stuff\n");
break;
case 2:
printf("do stuff\n");
break;
case 3:
printf("do stuff\n");
break;
default:
printf("Error !! Wrong Choice :- \n");
done = 1;
break;
}
}
return 0;
}
Here I used a variable initialized to 0 which indicates that the operation is not completed yet. When it's time to exit, the variable is set to 1, which causes the program to exit the while loop
Also, always remember to check the return value of printf(), to avoid possible errors
There is no break condition for while().
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void create();
void display();
void search();
struct node {
int data;
struct node* link;
};
struct node* head;
int main()
{
int value = 1;
while (value) {
printf("Enter Correct Choice :- \n");
printf("Enter 1 to Create Linklist :- \n");
printf("Enter 2 to Display Linklist :- \n");
printf("Enter 3 to Search Linklist :- \n");
printf("Enter 0 to exit :- \n");
printf("Enter Your Choice Here _________ ");
scanf(" %d", &value);
switch (value) {
case 1:
create();
break;
case 2:
display();
break;
case 3:
search();
break;
default:
printf("Error !! Wrong Choice :- \n");
break;
}
}
return 0;
}
if a non valid integer is enter for scanf(" %d", &value); value is not set and the invalid input is not flush => scanf will never block nor update value
you need to check scanf returns 1 (you read 1 value) and if not to flush the invalid input for instance reading all the line
so you can replace
scanf(" %d", &value);
switch (value) {
...
}
by
if (scanf("%d", &value) != 1) {
puts("invalid input");
while ((value = getchar()) != '\n') {
if (value == EOF) {
puts("EOF, exit");
exit(-1);
}
}
}
else {
switch(value) {
...
}
}
of course you can also manage the invalid input in your default case forcing an invalid value :
if (scanf("%d", &value) != 1) {
while ((value = getchar()) != '\n') {
if (value == EOF) {
puts("EOF, exit");
exit(-1);
}
}
value = -1; /* any value except 1,2 or 3 */
}
switch(value) {
...
}
Out of that you have no option to stop the execution, you can do :
...
puts("Enter 4 to exit :-);
...
switch (value) {
...
case 4:
exit(0);
...
}
I belive your intention is to run the program as long as "0" is not entered, but ter is no case for "0". also when we have scanf for %d and entering a "char" instead scanf will not read the char from buff. data on value will not get changed and it will keep printing existing data. (garbage if we enter invalid data first time itself, or any entered data.)
used fgets to read the input data, and do a scanf from buf, even when data is incorrect we are clearing the std input. so program will not get in to a infinite loop with scanf failure.
initilised "value = 0"
added case for "0".
scanf is replaced with fget +sscanf
#include <stdio.h>
#include <stdlib.h>
int main()
{
int value = 0;
char buff[256] = {0};
while (1) {
value = -1;
printf("Enter Correct Choice :- \n");
printf("Enter 1 to Create Linklist :- \n");
printf("Enter 2 to Display Linklist :- \n");
printf("Enter 3 to Search Linklist :- \n");
printf("Enter Your Choice Here _________ ");
fgets(buff, 255, stdin);
sscanf(buff, "%d", &value);
switch (value) {
case 1:
//create();
printf("case : 1\n");
break;
case 2:
//display();
printf("case : 2\n");
break;
case 3:
//search();
printf("case : 3\n");
break;
case 0 :
printf("case : 0 : Exiting program\n");
return 0;
default:
printf("Error !! Wrong Choice :- %d\n", value);
break;
}
}
return 0;
}
Im basically Writing a program that creates, reads, updates and
deletes records in a binary file.
Everything compiles correctly, no syntax errors, but I do have some
bugs.
KNOWN BUGS
1.) Imputing any strings does not work, using fgets
2.) Ctrl-D Does Work but outputs a 'default' error before it exits.
3.) Update does not work (Not my main issue at the moment as the others are more important for now.)
4?) I'm not sure if the menu is working how it's supposed to work. I
think the do while is correct, since in the menu if I select and hit
CTRL-D it does exit the program. Just wanna be sure.
Right now I just want to know why, It is skipping the courseName in
the inputs function.
Here is my code thus far
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
typedef struct{
char courseName [64];
char courseSched [4];
unsigned int courseHours;
unsigned int courseSize;} COURSE;
FILE *pfileCourse;
int courseNumber = 0;
//Prototypes
void inputDetails(COURSE *c);
void readCourseRecord();
void createCourseRecord();
void print_menu();
void modifyCourseInfo();
void deleteCourse();
void display(COURSE c);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char choice; // this is the choice
printf("Enter one of the following actions or press CTRL-D to exit\n");
printf("C - Create a new course record\n");
printf("R - Read an existing course record\n");
printf("U - Update an existing course record\n");
printf("D - Delete an existing course record\n");
do{
choice = getchar();
switch(choice) {
case 'c':
case 'C':
printf("YOU PICKED C for Create\n");
createCourseRecord();
break;
case 'r':
case 'R':
printf("This is Choice R\n");
readCourseRecord();
break;
case 'u':
case 'U':
printf("Here is where you update an existing course\n");
modifyCourseInfo();
break;
case 'd':
case 'D':
printf("here is where you Delete an existing course record\n");
deleteCourse();
break;
default:
printf("Wrong Choice!\n");
}
}while(choice != EOF);
return 0;
}
void createCourseRecord() {
COURSE data;
pfileCourse = fopen("courses.dat", "ab");
printf("Please Enter The Details of The Course\n");
inputDetails(&data);
fwrite(&data, sizeof(data), 1, pfileCourse);
fclose(pfileCourse);
printf("Course Has Been Created!\n");
}
void inputDetails(COURSE *c) {
printf("Enter a course number: \n");
scanf("%d", &courseNumber);
printf("Enter a Course Name: \n");
fgets(c->courseName, sizeof(courseName), stdin);
printf("Enter the course schedule (MWF or TR): \n");
fgets(c->courseSched, 4, stdin);
fflush(stdin);
printf("Enter the course credit hours: \n");
scanf("%d",&c->courseHours);
fflush(stdin);
printf("Enter Number of Students Enrolled: \n");
scanf("%d",&c->courseSize);
return;
}
void readCourseRecord(){
COURSE data;
int flag = 0;
int readCourseNumber = 0;
printf("Please Enter a Course Number to Display\n");
scanf("%d", &readCourseNumber);
fflush(stdin);
pfileCourse = fopen("courses.dat", "rb");
while((fread(&data, sizeof(data), 1, pfileCourse)) > 0) {
if(readCourseNumber == courseNumber)
{
display(data);
flag = 1;
}
}
fclose(pfileCourse);
if(flag == 0)
printf("Course not Found!\n");
}
void deleteCourse(){
int newCourseNum;
COURSE data;
FILE *file2;
printf("Please Enter The Course You Wish You Delete\n");
scanf("%d", &newCourseNum);
pfileCourse = fopen("courses.dat", "rb");
file2 = fopen("temp.dat", "wb");
rewind(pfileCourse);
while((fread(&data, sizeof(data), 1, pfileCourse)) > 0)
{
if(courseNumber != newCourseNum)
{
fwrite(&data, sizeof(data), 1, file2);
}
}
fclose(file2);
fclose(pfileCourse);
remove("courses.dat");
rename("temp.dat", "courses.dat");
printf("%d was Successfully deleted\n", newCourseNum);
}
void modifyCourseInfo()
{
COURSE data;
int newCourseNum, found = 0;
printf("Modify\n");
printf("Please Enter The Course You Wish You Modify\n");
scanf("%d", &newCourseNum);
pfileCourse = fopen("courses.dat", "rb+");
while ((fread(&data, sizeof(data), 1, pfileCourse)) > 0 && found == 0)
{
if (courseNumber == newCourseNum)
{
display(data);
printf("Please Enter New Details\n");
inputDetails(&data);
fseek(pfileCourse, - (long)sizeof(data), 1);
fwrite(&data, sizeof(data), 1, pfileCourse);
printf("Course Updated\n");
found == 1;
}
}
fclose(pfileCourse);
if(found == 0)
printf("ERROR: course not found\n");
}
void display(COURSE c){
printf("courseNumber:\t %d\n", courseNumber);
printf("courseName:\t %s\n",c.courseName);
printf("courseSched:\t %s\n",c.courseSched);
printf("courseName:\t %d\n",c.courseHours);
printf("courseSize:\t %d\n",c.courseSize);
}
It doesn't skip courseName, courseName just gets value '\n' because scanf function stops reading your input BEFORE white space. Scanf ignores any whitespace characters encountered before the next non-whitespace character. So you can just add
scanf("%d[^\n]", &courseNumber);
getchar();
after every scanf you have but I'd recommend you to use fgets function for every interactive input.
I am new in this world of programming. I am learning programming at my school. My teacher recently ask the class to create a menu with limited selection that will end with a sentinel value.
So here's my coding:
#include <stdio.h>
void menu(void);
void choice1();
void choice2();
void choice3();
char choice;
int main() {
do {
menu();
if (choice =='1')
choice1();
else if (choice =='2')
choice2();
else if (choice =='3')
choice3();
else if (choice =='4')
break;
else
printf("Invalid character.");
} while (choice != '4');
return 0;
}
void menu(void) {
printf("\nMenu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("3) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
scanf("%c", &choice);
}
void choice1() {
printf("\nChoice 1\n");
}
void choice2() {
printf("\nChoice 2\n");
}
void choice3() {
printf("\nChoice 3\n");
}
When I try to run it, by putting the number 1, 2, 3, the output came out but after that the function menu() and also the line "Invalid character." came out. As for as the other character, the menu() and the "Invalid character" came out twice. Number 4 does end the program. Is there any improvement that I can make to make sure the menu() and the line "Invalid character." does not come out unnecessarily?
In line-buffered input, the newline character lingers in the buffer after you read a single character for 'choice' and hence you get Invalid character. unintentionally.
You are required clear the buffer after reading the choice
scanf("%c", &choice);
while(getchar()!='\n')
/* Wasting the buffer
* Hence ensuring that the character you enter
* is indeed considered for 'choice'
*/
;; // Do nothing in particular
As a side note, your program looks like a typical use-case for the switch-case command and maybe your teacher expects you to use it.
Considering the scenario mentioned by #chqrlie in [ this ] comment, the workaround is to add after
scanf("%c", &choice);
the below lines
int c;
while ((c = getchar()) != EOF && c != '\n')
;; //Wasting the buffer
The problem is simple: the terminal is line buffered: you must press enter for the input to become available to your program, the first scanf("%c", &choice) retrieves the character typed and the second call retrieves the linefeed ('\n') that was generated by the enter key.
There are multiple ways to avoid this problem. You can add a space in the scanf format before the %c: scanf(" %c", &choice); or you can read characters after the first until you get a '\n'.
Note that you must check the return value of scanf to avoid undefined behavior if the user enters an end of file. It is also advisable to avoid global variables: the function menu() should return the choice specified. Using a switch statement is also more idiomatic for this.
Here is a corrected version:
#include <stdio.h>
int menu(void);
void choice1(void);
void choice2(void);
void choice3(void);
int main(void) {
int ch;
for (;;) {
switch (ch = menu()) {
case '1': choice1(); continue;
case '2': choice2(); continue;
case '3': choice3(); continue;
case '4':
case EOF: break;
default: printf("Invalid character %c\n", ch); continue;
}
break;
}
return 0;
}
int menu(void) {
char choice;
printf("\nMenu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("3) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
if (scanf(" %c", &choice) == 1)
return choice;
else
return EOF;
}
void choice1(void) {
printf("\nChoice 1\n");
}
void choice2(void) {
printf("\nChoice 2\n");
}
void choice3(void) {
printf("\nChoice 3\n");
}
As already mentioned in other answers the problem is the newline character.
When you press 1 followed by enter, you'll get two chars, i.e. 1 and \n. So your loop runs twice and prints Invalid character when \n is processed.
Here is an alternative solution for your problem. Just add a space before %c.
scanf(" %c", &choice);
This works because the space will match any number of white-space characters and thereby match the \n and remove it.
From the man page:
A sequence of white-space characters (space, tab, newline,
etc.......). This directive matches any amount of
white space, including none, in the input.
Additional comments
You should always check the value returned by scanf to make sure you read the correct number of values.
if (scanf(" %c", &choice) != 1)
{
// Add error handling ....
// For instance you could terminate the program like
exit(1);
}
In your program choice is a global variable. In general global variables should be avoid if possible. In your case you could make choice a local variable in main and let menu return a char. Like:
// char choice; Remove global variable
int main() {
char choice; // Add local variable
do {
choice = menu(); // Assign to local variable
.....
}
char menu(void) { // Make the function return a char
char choice; // Add local variable
printf("\nMenu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("3) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
if (scanf("%c", &choice) != 1) exit(1); // Assign to local variable
// On failure -> exit
return choice; // Return value of local variable
}
You can write scanf(" %c",&choice); (with whitespace) instead of scanf("%c",&choice);
When I try to run it, by putting the number 1, 2, 3, the output came
out but after that the function menu() and also the line "Invalid
character." came out.
It's happening because of the new line character you press after each number. It's itself a character and loop is iterated one more time for this. As it is an invalid character, that's why "Invalid character." is showing.
Try using getchar() after scanf().
Edit: fixed my previous while loop which may exit incorrectedly:
#include <stdio.h>
int main() {
int choice;
printf("Menu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("2) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
while (1) {
char c = scanf("%d",&choice);
if (c == EOF || choice == 4) break;
if (choice == 1 || choice == 2 || choice == 3) {
printf("Choice %d.\n", choice);
} else {
printf("Invalid character.\n");
}
}
return 0;
}
You can use function if you want, but not necessary in this case. You need to understand how many times your loop actually runs and compare it to that you expect.
My previous code:
#include <stdio.h>
int main() {
int choice;
printf("Menu:\n\n");
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("2) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
while (scanf("%d", &choice) && choice != 4) {
if (choice == 1 || choice == 2 || choice == 3) {
printf("Choice %d.\n", choice);
} else {
printf("Invalid character.\n");
}
}
return 0;
}
I'm new to programming in C. I have a quick question about Switch Statements.
I have a menu that presents a list of options like so:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 100
struct Video {
char name[1024]; // Yvideo name
int ranking; // Number of viewer hits
char url[1024]; // YouTube URL
};
struct Video Collection[MAX];
int tail = 0;
//-- Forward Declaration --//
void printall();
void insertion();
void savequit();
void load();
void branching(char);
void menu();
int main()
{
char ch;
load(); // load save data from file
printf("\n\nWelcome\n");
do {
menu();
fflush(stdin); // Flush the standard input buffer
ch = tolower(getchar()); // read a char, convert to lower case
branching(ch);
} while (ch != 'q');
return 0;
}
void menu()
{
printf("\nMenu Options\n");
printf("------------------------------------------------------\n");
printf("i: Insert a new favorite\n");
printf("p: Review your list\n");
printf("q: Save and quit\n");
printf("\n\nPlease enter a choice (i, p, or q) ---> ");
}
void branching(char option)
{
switch(option)
{
case 'i':
insertion();
break;
case 'p':
printall();
break;
case 'q':
savequit();
break;
default:
printf("\nError: Invalid Input. Please try again...");
break;
}
}
so far entering 'i' (for inserting a new entry) and q (for save and quit) work perfectly. However every time I enter 'p' I get the default case. (Error: Invalid Input. Please try again...). What is it that I am doing wrong? I believe the syntax for the switch is correct? I've tried changing the 'p' to a different letter and I still got the the default case. Here is my printall() method if that helps...
void printall()
{
int i;
printf("\nCollections: \n");
for(i = 0; i < tail; i++)
{
printf("\nName: %s", Collection[i].name);
printf("\nRanking (Hits): %d", Collection[i].ranking);
printf("\nURL: %s", Collection[i].url);
printf("\n");
}
}
What about something like:
char b[5];
do {
menu();
if(fgets(b,5,stdin)==NULL)
return -1;
ch = tolower(b[0]); // read a char, convert to lower case
while(strlen(b)>=4&&b[3]!='\n'){
check=fgets(b,5,stdin);
if(check==NULL)
return -1;
}
branching(ch);
} while (ch != 'q');
You can output the invalid char in your default case. That may help you understand how your input are handled.
default:
printf("\nError: Invalid Input ('%c'). Please try again...", option);
break;
fflush(stdin) is undefined as fflush is define only for output streams. To clear the newline char, you can simply use another getchar().
Try this for the loop part:
do {
menu();
ch = tolower((unsigned char)getchar());
getchar();
branching(ch);
} while (ch != 'q');