CODE:
#include <stdio.h>
main() {
int nums[100], i;
char answer;
int count = 0;
double avg;
for (i = 0; i < 100; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &nums[i]);
printf("Another? ");
scanf("%c", &answer);
count += nums[i];
}
}
RUN:
~> a.out
Enter number 1: 1
Another? Enter number 2: 2
Another? Enter number 3: 3
Another? Enter number 4: 4
Another? Enter number 5: 5
Another? Enter number 6: 6
Another? Enter number 7: 7
Another? Enter number 8: 8
Another? Enter number 9:
It's supposed to ask me if I want to enter another number, but for some reason the scanf is not working. Also, I need to make it so that the user can enter 100 numbers, or any number under that, being prompted with a question of "do you want to enter another number". If the answer is no, it terminates, if it is yes, it carries on.
Your first scanf leaves a newline in the buffer. It's because %d ignores trailing blanks while %c doesn't. Use this cheap trick to make the second scanf eat the blanks:
scanf(" %c", &answer);
^
The issue is common enough, you can read more about it in the C FAQ.
You need a space before the %c in order to skip the newline that wasn't read when scanf stopped at the end of the number.
I have some unsolicited advice...
Don't use scanf(3) directly, it's too hard to make it do what you want. It's usually better to use fgets(3) and then sscanf(3).
Compile with warnings turned on. (On my Mac that means cc -Wall ...)
And with warnings turned on, here your program with a few issues fixed:
#include <stdio.h>
int main(void) {
int nums[100], i;
char answer;
int count = 0;
// double avg;
for (i = 0; i < 100; i++) {
printf("Enter number %d: ", i + 1);
scanf(" %d", &nums[i]);
printf("Another? ");
scanf(" %c", &answer);
if (answer != 'y' && answer != 'Y')
break;
count += nums[i];
}
return 0;
}
Related
Hi I am new to programming and I got a trouble when I try to make a little change to the example in the book.
/* Chapter 3 Example, C Prime Plus */
#include <stdio.h>
int main(void)
{
char Letter, ch;
int intValue;
printf("Please enter a letter: \n");
scanf("%c", &Letter); /* user inputs character */
printf("The code for %c is %d.\n", Letter, Letter);
printf("Now is another we to implement the process: \n");
printf("RN, the value of ch is %c, and the value of intValue is %d\n", ch, intValue);
printf("Please enter a letter: \n");
scanf("%c", &ch);
intValue = ch;
printf("The code for %c is %d.\n", ch, intValue);
return 0;
}
When I run it, the outcome would be
Please enter a letter:
M
The code for M is 77.
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10.
and the part
"
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10. " will all come out without asking me to enter a value.
I want to know why and are there any other way to implement it that is different from examples in the book?
Thank you for your time!
Hi Matt_C and welcome to SO.
First, you don't need the second bloc of printfs and the scanf, it just trying to do the same thing and there is an order error.
Second, it is tricky when you try consecutive scanf, it holds the last key pressed (enter is the last key pressed = \n). This is why it skips the second scanf.
There a little solution for that, add a space at the beginning of the scanfs. Try this:
int main() {
char exit, letter;
while (1) {
printf("Please enter a letter: ");
scanf(" %c", &letter);
printf("\nThe code for '%c' is %d. \n\n", letter, letter);
printf("Exit ? (y/n): ");
scanf(" %c", &exit);
if(exit == 'y')
{
break;
}
system("clear"); // UNIX
//system("cls"); // DOS
}
}
Don't forget to choose one answer that you believe is the best solution to your problem.
I'm doing a practice 'do while' program where I want the user to enter three numbers and the program will print the sum on screen. After receiving the answer, the program will ask the user if he wants to enter another three numbers to get another answer, and so on. I'm fine with this.
If user enters anything other than an integer ("A,!,%") etc, I want the program to prompt the user to re-enter a number. See comments in program.
#include <stdio.h>
/*
Do - While
This program shall ask the user to enter
three numbers and print out the sum. Entering letters
or special characters will ask the user to re-enter that
number.
example:
Enter Number 1: 2
Enter Number 2: 5
Enter Number 3: 9
Answer is 16
...
Enter Number 1: 2
Enter Number 2: yum here user incorrectly enters letters
Enter Number 2: 8 re-prompted to enter number to continue
Enter Number 3: 9
Answer is 19
*/
int main(void) {
int a,b,c,ans,n;
do{
do{
printf("Enter Number 1: ");
scanf("%d", &a);
printf("\n");
}
while((a>0) || (a<0)|| (a==0));
do{
printf("Enter Number 2: ");
scanf("%d", &b);
printf("\n");
}
while((b>0) || (b<0)|| (b==0));
do{
printf("Enter Number 3: ");
scanf("%d", &c);
printf("\n");
}
while ((c>0) || (c<0)|| (c==0));
ans = a+b+c;
printf("Answer is %d\n\n", ans);
printf("Press 1 to start over, or 0 to quit...");
scanf("%d",&n);
printf("\n");
}while (n!=0);
return 0;
}
Your program contains multiple repeated sections. Since you are gathering three numbers, you should use a for loop which runs three times.
for (int i = 0; i < 3; i++) {
/* ... */
}
Inside the for loop, you're gathering the i+1-th number each time. If the user doesn't enter a valid number, you keep trying to gather it. So the do-while loop containing the printf and scanf will go inside the for loop.
for (int i = 0; i < 3; i++) {
do {
printf("Enter Number %d: ", i+1);
scanf( /* ... */ );
} while ( /* ... */ );
}
scanf returns the number of input items successfully read as an int. So the do-while loop should repeat as long as the return value of scanf is zero. We could store the return value in a variable and check the variable in the while (...);, but we can just move the scanf itself into the while (...);. We also need an array to store the three input numbers.
int n[3];
for (int i = 0; i < 3; i++) {
do {
printf("Enter Number %d: ", i+1);
} while (scanf("%d", n+i) == 0);
}
The rest of the program would loop over the array and store the sum of the elements. You would then output the sum. This approach is robust and maintainable as changing the amount of input numbers is easy and repeated or similar code sections are eliminated.
You can use fgets to get the input and use strtol() to cast the string the user input into an int. If strtol returns 0 when the user input does not start with a number or have a number in it. From there you can check if the user input is 0 and then reprompt the user until a is not 0.
*instead of scanf()*
char num1[5];
char *end;
fgets(num1, 5, stdin);
a = strtol(num1, &end, 10);
while( a = 0){
fgets....
}
I have an assignment in C language that requires to ask users to enter values to arrays. My idea is createing two different arrays which one contains integer values and the other holds character values. This is my code so far:
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type");
printf(" and Time Input:");
scanf("%c", &instrType[0]);
scanf("%d", &time[0]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
while (continued == 'Y' || continued == 'y')
{
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type ");
printf("Time Input:");
scanf("%c", &instrType[i]);
scanf("%d", &time[i]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
}
return 0;
}
The expected value should be: L1 L2 C3 U1
My Screenshot
The loop just stopped when I tried to enter new values and the condition did not check the value even I entered 'Y' meaning 'yes to continue' please help :(
You are comparing a string with a character that is instead of using scanf("%s",&continued) try using "%c"
The main problem is scanf("%c", &char) because scanf() after had read the input print a \n to pass at the next line, this cause that the next scanf() instead of reading your input, go to read \n, causing the failure in the reading of the input.
To avoid this problem put a space before %c ==> scanf(" %c", &char)
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
do
{
printf("L-lock a resource\n");
printf("U-unlock a resource\n");
printf("C-compute\n");
printf("Please Enter The Instruction Type and Time Input: ");
scanf(" %c%d", &instrType[i], &time[i]);
printf("Continue? (Y/N) ");
scanf(" %c", &continued);
i++;
} while (continued == 'Y' || continued == 'y');
return 0;
}
Other things:
Instead of i = i + 1 you can use i++
Instead of using a while() is better using a do{...}while() for saving some line of code.
You can concatenate more inputs in a single line ==> scanf(" %c%d", &instrType[i], &time[i])
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 new to C programming. I wrote a simple switch case but it is not executing as expected . Can some one tell me what is wrong here??
#include <stdio.h>
int main() {
int i;
char yes;
bool flag = true;
while(flag) {
printf("Enter the value");
scanf("%d",&i);
switch(i) {
case 1:
printf("Hi");
break;
case 2:
printf("Hello");
break;
}
printf("Enter Y or N to continue");
scanf("%c",&yes);
if (yes == 'N') {
flag = false;
}
}
return 0;
}
The result I am expecting is:
Enter the Value
1
Hi
Enter Y or N to continue
Y
Enter the Value
2
Hello
Enter Y or N to continue
N
But the result I am getting is :
Enter the value 1
HiEnter Y or N to continueEnter the value N
HiEnter Y or N to continue
When you hit Enter after typing in the first number, scanf read all numeric characters from the input stream except the newline character produced by that Enter hit. The newline character is not a part of the number. It is left in the input stream, unread, waiting for someone else to read it.
The next scanf("%c",&yes); discovered that pending newline charcter and it read it without waiting. The %c format specifier does not skip whitespace in the input, it just reads the first character it sees.
Replace your scanf with
scanf(" %c",&yes);
to make it skip whitespace. That way it will ignore that pending newline and actually wait for you to enter something.
In all your printf you need to add \n at the end.
For example on usage, see here: printf
This should work for you:
(You forgot all '\n' in your printf statements and add a space in your char scanf statements)
#include <stdio.h>
int main() {
int i;
char yes;
int flag = 1;
while(flag) {
printf("Enter the value\n");
scanf("%d",&i);
switch(i){
case 1:
printf("Hi\n");
break;
case 2:
printf("Hello\n");
break;
}
printf("Enter Y or N to continue\n");
scanf(" %c", &yes);
if (yes == 'N')
flag = 0;
}
return 0;
}
Output:
Enter the Value
1
Hi
Enter Y or N to continue
Y
Enter the Value
2
Hello
Enter Y or N to continue
N
It's not a problem with the switch statement. It's a problem with your output - there aren't line breaks ('\n'). For example, instead of printf("Hi"); you might want to have printf("Hi\n");, which adds a line space at the end.