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');
Related
When this program is executed and case 1 is chosen, a submenu will be displayed. In this submenu there is an option to go back to the main menu, now this isn't displaying properly when chosen as it seems to be displaying the main menu twice as well as the default. This is the code:
#include <stdio.h>
#include "functions.h" //calls the functions.h file
int switch1();
int switch2();
int main() {
//Declaring variable
char command;
do {
do {
printf(SPLIT);
printf("\nEnter choice to operate one of the following functions.\n");
printf("1 - Operate using integer representation\n");
printf("2 - Operate using textual representation\n");
printf("0 - Quit\n");
printf("Choice:");
scanf("%c", &command);
switch (command) {
case '1':
switch1(); //Executes function switch1
break;
case '2':
switch2(); //Executes function switch2
break;
case '0':
printf(SPLIT);
printf("\nQuitting.");
printf(SPLIT);
return 0; //Program stops
default: //Switch statement reaches default if no other cases are reached
printf("\nIncorrect input, please re-try.\nEnter choice\n");
break;
}
} while(command != '0');
} while (command < '0' || command > '2');
return 0;
}
int switch1() {
//Declaring variables
char command;
int *array, *iZeroed = NULL;
printf(SPLIT);
printf("\nInteger representation will be used!\n");
array = generate(); //Executes function generate and sets the return to be array
do {
do {
printf("\nChoose an option:\n");
printf("1) Shuffle the array\n");
printf("2) Sort the array\n");
printf("3) Zero an element from the array\n");
printf("4) Display previous zeroed out element\n");
printf("0) Go back to main menu\n");
printf("Choice:");
scanf(" %c", &command);
switch (command) {
case '1':
array = shuffle(array); //Executes function shuffle and sets the return to be the new array
break;
case '2':
array = sort(array); //Executes function shuffle and sets the return to be the new array
break;
case '3':
iZeroed = shoot(array); //Executes function shoot and sets the return to be the element changed to 0
break;
case '4':
target(iZeroed); //Executes function target
break;
case '0':
return 0;
default: //Switch statement reaches default if no other cases are reached
printf(SPLIT);
printf("\nIncorrect input. Please re-enter an option\n");
break;
}
} while (command != '0');
} while (command < '0' || command > '1');
return 0;
}
This is the output I am getting when I choose to go back to main menu:
====================================================================
Choose an option:
1) Shuffle the array
2) Sort the array
3) Zero an element from the array
4) Display previous zeroed out element
0) Go back to main menu
Choice:0
====================================================================
Enter choice to operate one of the following functions.
1 - Operate using integer representation
2 - Operate using textual representation
0 - Quit
Choice:
Incorrect input, please re-try.
Enter choice
====================================================================
Enter choice to operate one of the following functions.
1 - Operate using integer representation
2 - Operate using textual representation
0 - Quit
Choice:
Place a space character int the format string for scanf() before the input specifier %c, and it means scanf() should drop whitespace characters there.
You are already doing so in your switch1() function, so you should also do so in your main() function.
printf("Choice:");
scanf("%c", &command);
Make it " %c"
I've found out that you could write the list of characters that are (not)allowed as an input when using scanf().
I need a user to type one of the following letters: d, f, r, k, c
So what i did is the following, and it works actually exactly the way i want it to. it doesn't let the program go further until one of the allowed letters is eventually pressed:
scanf ("%[^cfrdk]", &skala);
after that i want to check which of those five letter was actually entered, and here i get the whole problem. i don't get what exactly happens to the variable skala but its value is obviously not the entered letter. as i try to print it, it prints nothing. The switch-case after that also always goes by default.
here is the whole code:
int main()
{
char skala;
float inval,cels, fahr, kelvin, rankine, delis;
printf("Choose the Skala. Enter:\n`C` for Celsius"
" \n`F` for Fahrenheit \n`D` for Delisle \n`K` for Kelvin \n`R` for Rankine"
" \n Enter the letter here —> ");
scanf ("%[^cfrdk]", &skala);
getchar();
//printf("You have entered correctly. %c", &skala); PRINTS NOTHING
switch (skala){
case 'c': printf("You've chosen Celsius\n");
break;
case 'f': printf("You've chosen Fahrenheit\n");
break;
case 'r': printf("You've chosen Rankine\n");
break;
case 'd': printf("You've chosen Delisle\n");
break;
case 'k': printf("You've chosen Kelvin\n");
break;
default:printf("ERROR: wrong input\n");
break;
}
printf ("Enter a value to be converted = ");
scanf("%f", &inval);
return 0;
}`
who can explain it what exactly happens to the variable in scanf when using the list of allowed characters. And what are the ways of solving the problem?
The do/while loop will repeat until a letter in the set of valid letters is input.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char skala;
char valid[] = "cfdkr";
float inval,cels, fahr, kelvin, rankine, delis;
int result = 0;
int clean = 0;
printf("Choose the Skala. Enter:\n`C` for Celsius"
" \n`F` for Fahrenheit \n`D` for Delisle \n`K` for Kelvin \n`R` for Rankine"
" \n Enter the letter here —> ");
do {
if ( ( result = scanf (" %c", &skala)) != 1) {
if ( result == EOF) {
fprintf ( stderr, "problem getting input\n");
return 1;
}
}
if (strchr ( valid, skala) == NULL) {
printf ( "enter your choice of %s\n", valid);
result = 0;
}
} while ( result != 1);
switch (skala){
case 'c': printf("You've chosen Celsius\n");
break;
case 'f': printf("You've chosen Fahrenheit\n");
break;
case 'r': printf("You've chosen Rankine\n");
break;
case 'd': printf("You've chosen Delisle\n");
break;
case 'k': printf("You've chosen Kelvin\n");
break;
default:printf("ERROR: wrong input\n");
break;
}
do {
printf ("Enter a value to be converted = ");
if ( ( result = scanf("%f", &inval)) != 1) {
while ( clean = getchar ( )) != '\n') {
if ( clean == EOF) {
fprintf ( stderr, "problem getting input\n");
return 1;
}
}
}
} while ( result != 1);
return 0;
}
I need a user to type one of the following letters: d, f, r, k, c
Code cannot control what the user types. Code needs to cope with unexpected input.
The below is bad code. If scanf() does encounter some non-cfrdk, it will save 1 or more of those characters into skala and then append a null character. skala being only a char, is the wrong type for reading strings - the type expected by %[]. Result: Undefined behavior (UB).
If use does type a cfrdk, then scanf ("%[^cfrdk]", &skala); will read nothing into skalla and return 0.
scanf ("%[^cfrdk]", &skala);
Better to simply read all user input. Be sure to handle '\n'
switch (getchar()){
case 'c': printf("You've chosen Celsius\n");
break;
case 'f': printf("You've chosen Fahrenheit\n");
break;
case 'r': printf("You've chosen Rankine\n");
break;
case 'd': printf("You've chosen Delisle\n");
break;
case 'k': printf("You've chosen Kelvin\n");
break;
case '\n': // ignore
break;
case EOF: // input is closed
return -1;
default: printf("ERROR: wrong input\n");
// break;
}
Even better as suggested by #hyde, read a line of user input with fgets() and then validate the input.
char buf[80];
if (fgets(buf, sizeof buf, stdin) == NULL) {
// Handle End-Of-File or Error
return -1;
}
char scale[2] = { 0 };
// Check for valid initial character, additional checks possible
if (sscanf(buf, "%1[cfrdk]") != 1) Handle_Bad_Input(buf);
else {
switch (scale[0]) {
...
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');
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.