I've written a program to compute the running sum of any numbers input by a user. I need to provide the user with an option to exit the program at any stage, which I'm not sure how to do. I was looking into it and think getchar() is what I need to use but I'm not sure, there seem to be a few ways to do it.
I basically want the user to be able to hit "e" on the keyboard if they want to exit the program, and it will terminate. The comments in the code are just ideas I had so I've left them there. Help appreciated, thanks. Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float number;
float sum = 0;
int i = 1;
//char exit [2] = {'e'};
//void exit (int status);
printf ("Please enter number or enter \"e\" to exit at any stage:\n");
scanf ("%f", &number);
// if user inputs string e, program will terminate
/* if (number == 'e')
{
printf ("Exiting the program...\n");
exit(0);
} */
while (i == 1)
{
sum += number;
printf ("Sum: %.2f\n", sum);
printf ("Please enter number:\n");
scanf ("%f", &number);
// if user inputs string e, program will terminate
/* if (number == 'e')
{
printf ("Exiting the program...\n");
exit(0);
} */
}
return 0;
}
replace
scanf ("%f", &number);
to
if(1!=scanf ("%f", &number)){
if (getchar() == 'e'){
printf ("Exiting the program...\n");
exit(0);
}
}
Related
I'm trying to read input from stdin in C, where the program performs a few tasks if the entered character is any key but "enter". I'm using a while loop, and it works fine when user only enters 1 char, but prints a line twice when they enter more than that (entering more than 1 char is fine, the program should generate a new number per each one -- so like if the user enters 'aaa', it generates 3 new numbers.)
So this is the ideal output after entering something like 'eeee'(and it works fine when you enter just one char):
CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):
but this is what actually happens when you enter 'eeee':
enter any key for call (q to quit, no enter): CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):
and this is the part of my code (minimal reproducible version):
#include <stdio.h>
#include <stdlib.h>
int main(void){
system("clear");
printf ("CallList: \n");
printf("enter any key for call (q to quit, no enter): ");
char c;
scanf(" %c", &c);
system("clear");
char quit = 'q';
int random;
srand(1063);
while (c != quit){
if (c != '\n') {
random = rand() % 75 + 1;
// does a few functions here, they don't print anything and don't use stdin
}
printf ("CallList: ");
// prints the call list here
printf("\n");
printf("enter any key for call (q to quit, no enter): ");
scanf(" %c", &c);
system("clear");
}
printf("Goodbye! \n");
exit(0);
}
what is causing this and how can I fix it?
Try this in your loop:
while (c != quit){
if (c != '\n') {
random = rand() % 75 + 1;
//here you can add things to your calllist
c = getchar();
}
else {
printf ("CallList: ");
// prints the call list here
printf("\n");
printf("enter any key for call (q to quit, no enter): ");
c = getchar();
system("clear");
}
}
I have written this simple program, which is supposed to calculate the factorial of a number entered by the user. The program should ask the user to stop or continue the program in order to find the factorial of a new number.
since most of the time user don't pay attention to CapsLock the program should accept Y or y as an answer for yes. But every time I run this program and even though I enter Y/y , it gets terminated !
I googled and found out the problem could be due to new linecharacter getting accepted with my character input so, I modified the scanf code from scanf("%c", &choice); to scanf("%c ", &choice); in order to accommodate the new line character , but my program is still getting terminated after accepting Y/y as input.
Here is the code . Please if possible let me know the best practices and methods to deal with these kinds of issues along with the required correction.
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
I'm a beginner in programming and I'm running this code in visual studio 2015.
Just modify your scanf like following:
printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
also you should use:
} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
NOTE:
Simple quote ' is used for characters and double quote " is used for string
Your second-last line has a string literal "y", which should be a character literal i.e. 'y':
} while (choice =="y" || choice =="Y");
This should be:
} while (choice =='y' || choice =='Y');
Also, your scanf() doesn't consume whitespace. Add a space before %c to make it ignore newlines or other spaces:
scanf(" %c", &choice);
Try doing the following even after the correction there are still some bugs in the code
In your code if you type 'Y' and recalculate a factorial it gives wrong answer as
int factorial is already loaded with the previous value
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace System;
using namespace std;
int calculateFactorial(int i);
int main()
{
int i;
char choice;
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
printf("\n The factorial of entered no is :\t %d", calculateFactorial(i));
printf("\n Do you want to continue (Y/N)?");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
int calculateFactorial(int i) {
int factorial = 1;
if (i == 0){
factorial = 1;
}else {
while (i > 0){
factorial = factorial*i;
i--;
}
}
return factorial;
}
I am rewriting the Guessing Game code from 'C Programming for Absoulute Beginners' to verify that the user has entered in a digit, using the isdigit() function.
The rest of the code works, in terms of error checking; but the moment that the user enters in a non-digit, the code goes into an infinite loop.
#include <stdio.h>
#include <stdlib.h>
#define NO 2
#define YES 1
main()
{
int guessGame;
guessGame = 0;
int iRandomNum = 0;
int iResponse = 0;
printf("\n\nWould you like to play \"The Guessing Game\"?\n\n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
do{
if(guessGame == YES){
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 and 10:\n\n ");
scanf("%d", &iResponse);
if(!isdigit(iResponse)){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
if(iResponse == iRandomNum){
printf("\nYou guessed right\n");
printf("\nThe correct guess is %d!\n", iRandomNum);
printf("\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
} else {
printf("\n\nSorry, you guessed wrong\n");
printf("\nThe correct guess was %d!\n", iRandomNum);
printf("\n\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
}
}
else {
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
scanf("%d", &iResponse);
}
}
else {
printf("\nThe window will now close. Try again later!\n");
exit(0);
}
}while(guessGame != NO);
}
The code goes into infinite loop as scanf() is unable to read an integer. The character you entered remains in the keyboard buffer.No more reading of integers is possible as long as the character is present in the buffer. scanf() simply returns the number of items read as 0 each time. Hence,the program does not wait for the user to enter data and infinite loop results.
scanf() returns number of items successfully read. So,you can simply check for the return value of scanf(), if its 1 then scanf() has correctly read an integer.
check = scanf("%d", &iResponse);
if(check == 1){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
and flush the buffer if wrong input is entered
else {
while (getchar() != '\n'); //flush the buffer
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
//scanf("%d", &iResponse);
}
no need to ask for input here, while loop will continue and prompt for input in the beginning
Trying taking the input in the form of string .. also u will have to compare the input in the form 'number' :)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a, b, checka, checkb;
printf ("enter a: ");
checka = scanf ("%d", &a);
printf ("enter b: ");
checkb = scanf ("%d", &b);
printf ("checka = %d\n", checka);
printf ("checkb = %d", checkb);
return EXIT_SUCCESS;
}
I was having this problem in a larger program but I wrote a quick test to see if I could fix it, which I can't.
Basically when anything other than an integer is entered for a scanf, the program just instantly skips and ignores every other scanf and just prints the rest of the program it sees, meaning I can't make checks with a while loop, or I just get an infinite loop as the scanf in the loop to fix the variable just gets skipped.
Obviously if integers are entered this particular program will just return 1 for the last two printfs, which is expected.
What am I doing wrong?
Thanks!
There is a reason why we should check scanf for errors, try this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a, b, checka, checkb;
printf ("enter a: ");
if((scanf ("%d", &a)) == 1){
checka = a;
}else{
printf("Error(1)!");
exit(EXIT_FAILURE);
}
printf ("enter b: ");
if((scanf ("%d", &b)) == 1){
checkb = b;
}else{
printf("Error(2)!");
exit(EXIT_FAILURE);
}
printf ("checka = %d\n", checka);
printf ("checkb = %d", checkb);
return EXIT_SUCCESS;
}
this is a follow on question from one I asked recently:
C Programming help - providing user with option to exit a program
I now have a new problem. I can get the program to exit if a user enters any letter which is great, but now if a number is entered nothing happens. The while loop doesn't seem to run..
Can you please have a look at my code and see if you can spot what's wrong, thanks. Also, ideally i'd like xterm's window to close if the user wishes to exit. I'd be greatful if anyone could show me how to do this. Anyway here's the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float number;
float sum = 0;
printf ("Please enter number or enter any letter to exit:\n");
scanf ("%f", &number);
// if user ENTERS a letter, program will terminate
if(1!=scanf ("%f", &number))
{
getchar();
printf ("Exiting the program...\n");
exit(0);
}
while (1)
{
sum += number;
printf ("Sum: %.2f\n", sum);
printf ("Please enter number or enter any letter to exit:\n");
scanf ("%f", &number);
// if user ENTERS a letter, program will terminate
if(1!=scanf ("%f", &number))
{
getchar();
printf ("Exiting the program...\n");
exit(0);
}
}
return 0;
}
As #BrianCain commented: you are calling scanf a second time in your if statement. If you entered a letter for the first scanf, it forces the second to immediately fail; if you entered a number for the first, then the second is waiting for you to enter another number.
I removed two of your scanf functions and it seems to fix the problem
#include <stdio.h>
#include <stdlib.h>
int main()
{
float number;
float sum = 0;
printf ("Please enter number or enter any letter to exit:\n");
// if user ENTERS a letter, program will terminate
if(1!=scanf ("%f", &number))
{
getchar();
printf ("Exiting the program...\n");
exit(0);
}
while (1)
{
sum += number;
printf ("Sum: %.2f\n", sum);
printf ("Please enter number or enter any letter to exit:\n");
// if user ENTERS a letter, program will terminate
if(1!=scanf ("%f", &number))
{
getchar();
printf ("Exiting the program...\n");
exit(0);
}
}
return 0;
}
The scanf in your if erased the value of the previous one you did.
While the previous two answers are essentially correct, the simple (and clear) version would be:
if(number == 1)
break;
Place this right after your original scanf() and get rid of the other if(..) ..; condition entirely. This will test to see if the number '1' was entered, and if so will break the infinite loop, allowing the program to continue down to the return 0; statement.
It will also deal with what could be confusing style, which is having an exit condition (the final return 0;) that's essentially impossible to get to, or should be.