When I enter 0 the program ends. But there is getchar() in if statement and it doesn't work, can you help me?
On case 0 I want it to get char from user. If 'N' or 'n' is entered the program will end but if not the program will start over again. (from sec1).
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
sec1:
printf("Select a number between 4 and 0: ");
scanf("%d[\n]", &n);
switch(n)
{
case 0:
puts("Are you sure?");
puts("Yes(Y) or No(N)");
if(getchar() == 'N') goto sec1;
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
puts("Only numbers between 4 and 1 are accepted!");
goto sec1;
break;
}
system("pause");
return 0;
}
working one
int main()
{
int n, c;
sec1:
printf("Select a number between 4 and 0: ");
scanf("%d/n", &n);
switch(n)
{
case 0:
puts("Are you sure?");
puts("Yes(Y) or No(N)");
fflush(stdin);
if (getchar() == 'N') goto sec1;
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
puts("Only numbers between 4 and 1 are accepted!");
goto sec1;
break;
}
system("pause");
return 0;
}
Change
scanf("%d[\n]",&n);
to
scanf("%d\n",&n);
The reason that your original code does not work is because scanf wants to read an integer, a "[", a "\n" and a "]". So when you input an integer followed by a "\n", scanf only takes the integer(because it expects to see a "["). Then the getchar will simply take the remaining "\n". That's why your getchar() seems not working.
Hope it is helpful to you!
Probably you have some symbols in the input buffer when you are reading "N" or "n". You need to flush an input buffer before new reading. See this question for details.
Briefly just write:
while (getchar() != '\n') {}
right after scanf(...).
I guess this is the terminal which is in cooked mode, thereby only feeding typed characters to the program when the user completes a line by hitting return. You can test it by feeding it input from a pipe instead of interactively from the terminal.
Related
i am making a small project in which I have to convert different values to different bases like 10,8,16.But the problem is that I want to run the program till the user press 6 but if user hit Enter key then too it is waiting for the input rather than simply terminating. I'm using C11 version of C on online compiler.
and here's my code.
#include "ConvertInBackgnd"
#include<stdio.h>
int main() {
int choice;
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
l1: printf("Input your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
dec_bin();
break;
case 2:
bin_dec();
break;
case 3:
dec_octal();
break;
case 4:
octal_dec();
break;
case 5:
dec_hex();
break;
case 6:
goto l1;
default:
printf("Invalid choice.");
break;
}
printf("Input 6 for reconverting the values.");
scanf("%d", &choice);
if (choice == 6) {
goto l1;
} else
return 0;
return 0;
}
I have made a separate file in which I have made functions and I thought it isnot necessary to put that code here too.
Consider using fgets to take input into a character array.
If needed, the input can be parsed with sscanf, strtol or others.
#include<stdio.h>
int main() {
char line[100] = "";
do {
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
printf("Input your choice : ");
fgets ( line, sizeof line, stdin);
switch ( line[0]) {
case '1':
printf ( "dec_bin()\n");
break;
case '2':
printf ( "bin_dec()\n");
break;
case '3':
printf ( "dec_octal()\n");
break;
case '4':
printf ( "octal_dec()\n");
break;
case '5':
printf ( "dec_hex()\n");
break;
case '6':
case '\n':
break;
default:
printf("Invalid choice.");
break;
}
if ( line[0] != '\n') {
printf("Input 6 for reconverting the values.");
fgets ( line, sizeof line, stdin);
}
} while ( line[0] == '6');
return 0;
}
To solve the enter problem:
scanf("%d", &choice)
Right now you are taking int value, try with char value and match the enter key with it. Then you'll be able to do what you are trying to do.
Ok, So I wanted to terminate the program if Enter key is pressed. So I was first a newbie then I realized that itsnot a big deal and to do so I just need to take a char as Input and then check that if that char input is enter key or not.
Its a sample code to terminate the program after pressing enter key.
char line;
scanf("%c",&line);
if(line=='\n')
return 0;
else
// your other code
But if your program doesnot take input then you should clear the buffer before the above provided code by adding just this single line before the above code.
while(getchar()!='\n');
I'm very new to C programming, and I need a help!
I have made a program of calculator with the help of Switch Statement and I want this program to be in a loop, So that it ask the menu (i.e Enter your Choice: Divide,Multiplication,Addition etc) again and again with the user.
Also I want, an End option with the Cases in Menu, which will close the program. I don't know how to code that End option which will make the Program Close.
Please Help!
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,choice;
float sum,mul,div,sub,quo;
printf("\n\t\t\t\t CALCULATOR");
printf("\nEnter the First Number: ");
scanf("%d",&a);
printf("Enter the Second Number: ");
scanf("%d",&b);
printf("\n Enter Your Choice");
printf("\n\n1.Sum");
printf("\n2.Multiplication");
printf("\n3.Division");
printf("\n4.Subtraction");
printf("\n5.Quotient");
printf("\nYOUR CHOICE: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
sum=a+b;
printf("Sum= %f\n",sum);
break;
case 2:
mul=a*b;
printf("Multiplication= %f\n",mul);
break;
case 3:
div=a/b;
printf("Division= %lf\n",div);
break;
case 4:
sub=a-b;
printf("Subtraction= %f\n",sub);
break;
case 5:
quo=a%b;
printf("Quotient= %f\n",quo);
break;
default:
printf("\n Unavailable Choice");
}
return 0;
getch();
}
Assuming you add option number 6 to close the calculator, you can add the following case to quit the program -
case 6:
// print bye message or whatever
exit(0);
break;
You can read about the exit function and what the arguments passed to it mean. Usually a 0 indicates successful exit from the program.
You also need to include stdlib.h if you want to use exit.
I would suggest introducing a loop condition variable, eg. CarryOn, initialise it to 1, and use that in a while loop. Let the loop continue as long as the variable is 1. When the user selects "End", set the variable to 0 in the case. That will end the loop.
Let me clarify it with some example code outline:
int CarryOn = 1;
while (CarryOn == 1)
{
// ...your original code
// ...
// add to switch
case 6: // 6 will be the "End" / "Exit" option
CarryOn = 0;
break;
}
You will need to have a while loop.
while(true){
printf("\n\t\t\t\t CALCULATOR");
printf("\nEnter the First Number: ");
scanf("%d",&a);
....
//return 0; remove the return statement
getch();
}
and also add the menu item 6) Exit to your printf and handle that option as described in the one of the answers above.
case 6:
// print bye message or whatever
exit(0);
break;
I'm sorta having a problem with my code. The function will not terminate and it keeps looping forever. I'm kinda new when it comes to compiling C in Linux (I came from Dev-C++..)
Here's the code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 10
struct student{
char lname[20];
char fname[20];
int idnum[8];
int year;
};
struct course{
char cname[4];
struct student stud[MAX];
};
int main()
{
struct course c[0];
userSelect(&c);
return 0;
}
int userSelect(struct course *p_course)
{
int z=0, x;
printf("1 - Create course\n2 - Edit course\n3 - Add student(s)\n4 - Edit student data\n5 - Delete\n6 - Quit");
scanf("\n%d", &x);
while(z==0){
switch(x){
ccase 1: userCreateCourse(p_course);
break;
//case 2: userEditCourse(&c);
//break;
//case 3: userCreateStudents(&c);
//break;
//case 4: userEditStudents(&c);
//break;
case 6: printf("bye");
z++;
break;
default: printf("Invalid input");
break;
}
}
}
int userCreateCourse(struct course *p_course)
{
int *cnum=0, i;
cnum=(int *)malloc(sizeof(int));
cnum++;
printf("Enter course (ex: BSCS): ");
fgets(p_course[*cnum-1].cname, sizeof(p_course[*cnum-1]), stdin);
puts(p_course[*cnum-1].cname);
}
If I select 1, this is the output:
1 - Create course
2 - Edit course
3 - Add student(s)
4 - Edit student data
5 - Delete
6 - Quit1
Enter course (ex: BSCS): H��4k
Enter course (ex: BSCS): AAAA
AAAA
Enter course (ex: BSCS): AAAA
AAAA
Enter course (ex: BSCS):
and it keeps doing that endlessly until I close the terminal. I really don't know what's wrong.. Someone help :(
You need to read x inside the loop. What happens is that x remains the same value that you inputted the very first time. So case 1: is always executed.
You can use a do-while loop like:
do{
printf("1 - Create course\n2 - Edit course\n3 - Add student(s)\n4 - Edit student data\n5 - Delete\n6 - Quit\n");
scanf("\n%d", &x);
switch(x){
case 1: userCreateCourse(p_course);break;
//case 2: userEditCourse(&c);break;
//case 3: userCreateStudents(&c);break;
//case 4: userEditStudents(&c);break;
case 6: printf("bye");z++;break;
default: printf("Invalid input");break;
}
} while( z==0);
But remember there are a number of issues with the scanf() + fgets() approach.
The scanf() that reads x will leave a newline in the input buffer and fgets() will return immediately without reading input (due to \n).
You can handle this by discarding any input chars left in the input with:
.
int c;
while((c=getchar()) != '\n' && c!=EOF);
(just before fgets() call).
If you input non-numbers input for x, then you'll end up with an infinite loop since scanf() doesn't ignore invalid input(s). You should check the scanf() return value and discard (using getchar() as above) all input chars if it failed.
You should ask for a new x inside the while loop if you want to be able to input a new one. Otherwise the first x will be used time and again since you never exit the loop.
Well it does breaks but it comes back again in your loop since z == 0 remains true. It breaks out of your switch case, not out of your loop. At the end of the switch you should change the value of z for something different than 0 like :
while(z==0){
switch(x){
case 1: userCreateCourse(p_course);break;
//case 2: userEditCourse(&c);break;
//case 3: userCreateStudents(&c);break;
//case 4: userEditStudents(&c);break;
case 6: printf("bye");z++;break;
default: printf("Invalid input");break;
}
z = 1;
}
It'd be best for you to use a boolean like
boolean done = false;
while(!done){
switch(smth){
// do smth
}
done = true
}
I am implementing a polynomial using array. This is the Problem Statement:
Write a menu-driven program to represent Polynomials as a data structure using arrays. and write functions to add, subtract and multiply two polynomials; multiply a polynomial with a constant, find whether a polynomial is a "zero- polynomial, return the degree of the polynomial. Assume that a new polynomial is created after each operation. How would you input and output polynomials?
I have created the input and output functions. But my do while loop is running twice.. Help me finding out why.
The do-while loop
do{
print_menu();
scanf("%c",&ch);
printf("\nch = %c\n",ch);
switch(ch){
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
}while(ch != 'q');
return 0;
}
The print_menu() function
void print_menu()
{
printf("\n1. Create a new polynomial.");
printf("\n2. Print polynomial.");
printf("\nq. Exit");
printf("\nEnter Choice:");
}
The create_poly() function
void create_poly(int poly[][2], int termpool[][2], int *next_poly)
{
int beg = poly[*next_poly][0];
int end, size, i, j;
printf("Enter size of the polynomial:");
scanf("%d",&size);
poly[*next_poly][1] = beg + size - 1;
end = poly[*next_poly][1];
printf("Enter terms of the polynomial(coeff then exponent):\n");
for(i=beg; i<=end; i++){
for(j=0; j<2; j++){
scanf("%d ",&termpool[i][j]);
}
}
poly[++(*next_poly)][0] = end + 1;
}
The print_poly() function
void print_poly(int poly[][2],int termpool[][2],int *next_poly)
{
int pos,beg,end;
int i;
printf("Enter position of the polynomial:");
scanf("%d",&pos);
if(pos-1 > *next_poly){
printf("Invalid position.");
return;
}
beg = poly[pos-1][0];
end = poly[pos-1][1];
for(i=beg; i<=end; i++){
printf(" %dx^%d +",termpool[i][0],termpool[i][1]);
}
printf("\b = 0");
}
Here is a sample output:
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:1
ch = 1
Enter size of the polynomial:2
Enter terms of the polynomial(coeff then exponent):
2 4
6 7
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:
ch =
Invalid choice.
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:q
ch = q
Tried flushing the stdin… The problem stays. Printing the value of ch in each step, I think it is a whitespace. Where does the white space comes?
The answer to abnormal behavior of scanf answers this question also.
If you test the next code you will note the same problem
int main() {
char c;
do {
scanf_s("%c", &c);
if (c != 'q')
printf("test scanf() function\n");
} while (c);
}
the scanf() function works when the enter key is pressed, but this insert another char in the buffer input, the char of new line '\n', it is taken again by scanf() because the loop block. Try to change the previous code by this code:`
do {
scanf_s("%c", &c); // or c = getchar();
switch (c){
case '\n':
break;
default:
printf("test scanf() function\n");
}
} while (c);`
and will work fine. In your code only add a new case in the switch block:
switch(ch) {
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case '\n':
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
sorry, English is not my native language
There's an extra character waiting to be consumed after you make your initial choice, that's why the loop is executing twice.
See this question on the comp.lang.c FAQ
I have been able to do switch case program but I want program to run again and again until a user selects to quit.
I basically wants program to run again and again using do while loop...
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
Use a do...while loop like this:
int I = 1; //Initialize to some non-zero number to prevent UB
printf("Enter 0 to quit \n");
do{
if (scanf("%d",&I) != 1) //If invalid data such as characters are inputted
{
scanf("%*[^\n]");
scanf("%*c"); //Clear the stdin
}
} while(I!=0); //Loop until `I` is not 0
This piece of code will loop until the user enters 0. You can change this code according to your needs. If you want your switch in this, copy your posted code after the scanf.
The loop will run until you enter -1 as input.
#include<stdio.h>
int main()
{
int I;
do
{
puts("Enter -1 to quit");
printf("Enter your choice: ");
scanf("%d",&I);
switch(I)
{
case 1:
printf("67\n");
break;
case 2:
printf("45\n");
break;
case -1:
puts("Bye");
break;
default:
printf("default\n");
}
}while(I != -1);
return 0;
}
this program runs untill user gives input 0 or a negative number...
#include<stdio.h>
int main()
{
int I;
do
{
scanf("%d",&I);
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
}
while(I>0);
return 0;
}
Simple Use of Do-While Loop.
Choice is the variable in which user's choice will be stored, whether he wants to print the statement again or not.
int choice;
do{
printf("\nHello World!"); //This is the task of the program (Replace it with your task)
printf("\nDo You Want to Print it again ? 1 Yes/0 No: ");
scanf("%d",&choice);
}while(choice==1); //Loop will exit when choice gets value other than 1
// here switch will run until A is not equal to S
int N;
char A;
do{
cin>>N;
N = N%7;
cout<<endl;
cin>>A;
switch(N)
{
case 1: cout<<"Monday"<<endl; break;
case 2: cout<<"Tuesday"<<endl; break;
case 3: cout<<"Wednesday"<<endl; break;
case 4: cout<<"Thursday"<<endl; break;
case 5: cout<<"Friday"<<endl; break;
case 6: cout<<"Saturaday"<<endl; break;
case 0: cout<<"Sunday"<<endl; break;
default: cout<<"Invalid Input"; }}
while(A!='S');