How to end a program with a character in C programming.
I have this sample program below, which I would like to add a character like ' F' that ends the program when the user inputs that character.
#include %26lt;stdio.h%26gt;
#include %26lt;math.h%26gt;
int main(){
int binary=0;
int decimal=0;
int digits=0;
while(1){
printf("Input in Binary: ");
fflush(stdin);
scanf("%i",%26amp;binary);
for(int i=1;binary%26gt;=i;i*=10){
digits++;
}
for(int i=(digits-1);i%26gt;=0;i--){
if((binary-pow(10.0,i))%26gt;=0){
decimal+=1%26lt;%26lt;i;
binary-=pow(10.0,i);
}
}
digits=0;
printf("\nOutput in decimal: %i\n\n",decimal);
}
return 0;
}
the problem is that the variable "binary" is of integer, I need to switch it to character, but it should still work.
I tried doing this:
if(binary=='f')
break;
but since binary is integer, when I enter f, the program keeps looping and it does not stop.
How can I solve this issue?|||After you do the final output, ask the user if they want to continue or not in such a way that a 'F' indicates no. Then, instead of doing a while (1) (which is bad coding -- it not only forces the loop to end from scattered places within itself, it also shows the coder didn't really know how the loop was going to work), do this:
char Response = ''; // Note: Those are two single quotes, not one double quote.
while ( Response != 'F' %26amp;%26amp; Response != 'f' )
{
// Ask here and read the answer into Response
}
Hope that helps.|||Use char instead of int, but make a seperate variable for doing this.
Char exitProgram;
At the end of the program, just grab the users input when asked to quit, and run it through an if/then/else loop.|||I added a new variable "char binarychar" and changed the way you get the user input by a bit. This time, the scanf "tries" to get the user input and checks to see whether the input is even correct or not. If the input was truly a number, then the scanf returns true, and thus the if statement i used does not activate. Otherwise, if the userinput was "not" a number, then the scanf would return false, thus triggering the if statement. And inside the if statement, it assumes that if the userinput was not a number, then it must be a character. And so, it attemps to scanf a character. If the character is an 'f' or 'F', then it breaks the loop and thus reaches the end of the program.
#include %26lt;stdio.h%26gt;
#include %26lt;math.h%26gt;
int main(){
int binary=0;
int decimal=0;
int digits=0;
char binarychar;
while(1){
printf("Input in Binary: ");
fflush(stdin);
if(scanf("%i",%26amp;binary)==false){
scanf("%c",%26amp;binarychar);
if((binarychar=='f')
||(binarychar=='F')){
break;
}
}
for(int i=1;binary%26gt;=i;i*=10){
digits++;
}
for(int i=(digits-1);i%26gt;=0;i--){
if((binary-pow(10.0,i))%26gt;=0){
decimal+=1%26lt;%26lt;i;
binary-=pow(10.0,i);
}
}
digits=0;
printf("\nOutput in decimal: %i\n\n",decimal);
}
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment