pls help me how to make my program repeatable
char name[99];
printf("Please Input your Complete Name: ");
scanf(" %[^\n]",name);
printf("%s\n", name);
printf("enter y or Y to continue");
scanf("%c", &redo);
while((redo == 'y') || (redo == 'Y'));
is my code is correct ? correct me if im wrong
The while at the bottom is a loop with an empty body because you have a ; right after the condition instead of a statement or a bracketed group of statements.
For this you actually want do..while, which will run the loop at least once:
char redo;
char name[99];
do {
printf("Please Input your Complete Name: ");
scanf(" %[^\n]",name);
printf("%s\n", name);
printf("enter y or Y to continue");
scanf("%c", &redo);
} while((redo == 'y') || (redo == 'Y'));
Related
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])
Okay so I have run a function 4 times. It runs perfectly the first time but when i have to run that function again the 3 other time, i get the "* INVALID ENTRY * : " printf that i made when the user doesnt input a 'y' or 'Y' or 'n' or 'N'
Also, I am trying to make it so that whenever a user enters "Yes or No" it will prompt the "error message" but currently the way i wrote my program it takes only the first Character from the user" Ex: Inputs "Yes" the program will take only "Y" which makes the program think the user entered 'Y' which skips the error stage.
This is what is in my main
printf("Please enter 'Y' > ");
printf(" Result: %d\n", yes() );
printf("Please enter 'y' > ");
printf(" Result: %d\n", yes());
printf("Please enter 'N' > ");
printf(" Result: %d\n", yes());
printf("Please enter 'yes', then 'no', then 'n' > ");
printf(" Result: %d\n", yes());
And this is my part im trying to access.
int yes(void) {
char singleLetter;
int theResults = 0;
scanf("%c", &singleLetter);
while ((singleLetter != 'y') && (singleLetter != 'Y') && (singleLetter != 'n') && (singleLetter != 'N')) {
clearKeyboard();
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
scanf("%c", &singleLetter);
}
if ((singleLetter == 'y') || (singleLetter == 'Y')) {
theResults = theResults++;
}
if ((singleLetter == 'n') || (singleLetter == 'N')) {
theResults = 0;
}
//printf("%c",singleLetter);
return theResults;
}
The results are:
Please enter 'Y' > Y
Result: 1
Please enter 'y' > y
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: y
Result: 1
Please enter 'N' > N
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: N
Result: 0
Please enter 'yes', then 'no', then 'n' > yes
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: no
Result: 0
EDIT::
I fixed the above code so it works fine
However when I call yes() from a different function i get this error:
This is the code im trying to call from:
void getName(struct Name *contactName) {
printf("Please enter the contact's first name: ");
scanf("%s", (*contactName).firstName);
printf("Do you want to enter a middle intial(s)? (y or n): ");
yes();
if (yes() == 1) {
printf("Please enter the contact's middle intial(s): ");
scanf("%s", (*contactName).middleInitial);
}
printf("Please enter the contact's last name: ");
scanf("%s", (*contactName).lastName);
}
I fixed the yes() code with
int yes(void) {
char singleLetter;
int theResults = 0;
scanf("%c", &singleLetter);
clearKeyboard();
while ((singleLetter != 'y') && (singleLetter != 'Y') && (singleLetter != 'n') && (singleLetter != 'N')) {
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
scanf("%c", &singleLetter);
clearKeyboard();
}
if ((singleLetter == 'y') || (singleLetter == 'Y')) {
theResults = theResults + 1;
}
if ((singleLetter == 'n') || (singleLetter == 'N')) {
theResults = 0;
}
return theResults;
}
i get this error. Literally makes me enter y 3 times, and i get a invalid entry code for no reason.
Do you want to enter a middle intial(s)? (y or n): y
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: y
y
Please enter the contact's middle intial(s):
EDIT PART 2
I fixed my function yes() by doing this:
int yes(void) {
char singleLetter = ' ';
int finalValue = -1;
int theResult = 0;
scanf(" %c", &singleLetter);
clearKeyboard();
do
{
switch (singleLetter)
{
case 'Y':
case 'y':
finalValue = 1;
theResult = 1;
break;
case 'N':
case 'n':
finalValue = 0;
theResult = 1;
break;
default:
theResult = 0;
printf("Only (Y)es or (N)o are acceptable: ");
scanf("%c", &singleLetter);
clearKeyboard();
}
} while (!theResult);
return finalValue;
}
And this is the code im not sure with NEAR THE END OF THE CODE:
void getName(struct Name *contactName) {
printf("Please enter the contact's first name: ");
scanf("%s", (*contactName).firstName);
printf("Do you want to enter a middle intial(s)? (y or n): ");
if (yes() == 1) {
printf("Please enter the contact's middle intial(s): ");
scanf("%s", (*contactName).middleInitial);
}
printf("Please enter the contact's last name: ");
scanf("%s", (*contactName).lastName);
}
// getAddress:
void getAddress(struct Address *
contactAddress) {
printf("Please enter the contact's street number: ");
(*contactAddress).streetNumber == getInt();
printf("Please enter the contact's street name: ");
scanf(" %[^\n]", (*contactAddress).street);
printf("Do you want to enter an apartment number? (y or n): ");
if (yes() == 1) {
printf("Please enter the contact's apartment number: ");
scanf("%d", (*contactAddress).apartmentNumber);
}
printf("Please enter the contact's postal code: ");
scanf(" %[^\n]", (*contactAddress).postalCode);
printf("Please enter the contact's city: ");
scanf("%s", (*contactAddress).city);
}
// getNumbers:
// getNumbers:
// NOTE: Also modify this function so the cell number is
// mandatory (don't ask to enter the cell number)
void getNumbers(struct Numbers *contactNumber) {
printf("Please enter the contact's cell phone number: ");
scanf(" %s", (*contactNumber).cell);
printf("Do you want to enter a home phone number? (y or n) ");
if (yes() == 1) {
printf("Please enter the contact's home phone number: ");
scanf("%s", (*contactNumber).home);
}
printf("Do you want to enter a business number? (y or n) ");
if (yes() == 1) {
printf("Please enter the contact's business phone number: ");
scanf("%s", (*contactNumber).business);
}
printf("\n");
}
AND BELOW THAT I HAVE THIS AND DONT KNOW WHAT TO DO. AS I STATED IN THE COMMENT:
The purpose of this function is to set the values for a Contact using
the pointer parameter variable (set the Contact it points to).
Use the pointer parameter received to this function to supply the appropriate
Contact member to the “get” functions (getName, getAddress, and getNumbers) to set the values for the Contact.
void getContact(struct Contact *contact) {
getName(contact);
getAddress(contact);
getNumbers(contact);
}
THE BELLOW IS WHATS BEING ACCESSED/PRINTED. Whatever i enter, it doesnt show up because of void getContact(struct Contact *contact){ }
getContact(&contact);
printf("\nValues Entered:\n");
printf("Name: %s %s %s\n", contact.name.firstName, contact.name.middleInitial, contact.name.lastName);
printf("Address: %d|%s|%d|%s|%s\n", contact.address.streetNumber, contact.address.street,
contact.address.apartmentNumber, contact.address.postalCode, contact.address.city);
printf("Numbers: %s|%s|%s\n", contact.numbers.cell, contact.numbers.home, contact.numbers.business);
scanf retains the newline \n in the buffer, the next time scanf is executed, the newline is read instead. Consider this program:
#include <stdio.h>
int main(void)
{
char x;
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
return 0;
}
The output for the input w<ENTER>s<ENTER>
w
119: 'w'
10: '
'
In ASCII 119 is 'w' and 10 is '\n'.
If you add a getchar() after the scanf, then getchar() reads the newline
and then nothing is in the buffer left, then the next scanf waits for the user input again:
#include <stdio.h>
int main(void)
{
char x;
scanf("%c", &x);
getchar(); // <-- look here
printf("%d: '%c'\n", x, x);
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
return 0;
}
with the same input I get
w
119: 'w'
s
115: 's'
So, to solve your problem, you can add a getchar() after every scanf.
The best way to clear the buffer after using scanf:
int c;
while((c = getchar() !='\n') && c !=EOF );
EDIT
How to use fgets
man fgets
#include <stdio.h>
char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and stores them into the buffer
pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into
the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
Simply to get a line, you do:
char line[1024];
fgets(line, sizeof line, stdin);
fgets will returns NULL when there is no more lines to read or there is an
error. Either way when that happens, you usually stop reading the file. That's
why to read all lines from a file (or multiple lines from the user), you do
this:
char line[1024];
while(fgets(lines, sizeof line, stdin))
{
// do the work here
}
Bear in mind, that sizeof line in fgets is only correct, when line is an
array. If you for example allocate memory with malloc, you cannot use
sizeof line. If you get a pointer, then you have to know in advance how much
you can read.
size_t n = <some value>; // the value is not imporant,
// could be 100, could be 985
char *line = malloc(n);
if(line == NULL)
{
// error handling, for example return error value
}
// only if line is not NULL
fgets(line, n, stdin); // here I know the size in advance
// or as argument
void foo(char *buffer, size_t size)
{
fgets(buffer, size, stdin);
...
}
If the length of the line is lesser than the size (minus 1) of the buffer, the
newline character will be stored in the buffer. If you don't need it, you can
set it to 0 in order to get rid of the newline:
char line[1024];
fgets(line, sizeof line, stdin);
int len = strlen(line);
if(line[len - 1] == '\n')
line[len - 1] = 0;
But if you don't mind having the newline, then you don't have to do that.
So you could write your yes function with fgets. Get the whole line, even
if you are only interested in the first character, you can ignore the rest of
the characters in the line.
#include <ctype.h>
int yes(void) {
int theResults = 0;
char line[1024];
if(fgets(line, sizeof line, stdin) == NULL)
{
fprintf(stderr, "could not get line, aborting\n");
return -1; // error value
}
while(toupper(line[0]) != 'Y' && toupper(line[0]) != 'N') {
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
if(fgets(line, sizeof line, stdin) == NULL)
{
fprintf(stderr, "could not get line, aborting\n");
return -1; // error value
}
}
if(toupper(line[0]) == 'Y')
theResults++;
else
theResults = 0;
return theResults;
}
I have been working on a college project. I want user to enter Y/N if he wants to continue or not, so I wrote following code
repeat:
pr=0;
q=0;
res=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
billing(pr,q);
printf("Continue Shopping? (y/n) ");
scanf("%d",&res);
if(res=='y')
goto repeat;
else
return 0;
}
The problem is entering y executes else statement. I tried replacing y with 1,2,3.... and it works but I want it to work with Y or y or yes.
There is a bug in this line
scanf("%d",&res);
It should be
scanf(" %c",&res);
The formatting placeholders for char is %c not %d
scanf("%d",&res);
should be
scanf(" %c",&res);
As suggested by multiple users do while should be used over goto, so better code would be
do{
pr=0;
q=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
billing(pr,q);
printf("Continue Shopping? (y/n) ");
scanf(" %c",&res);
}
while(*res == 'Y' || *res == 'y');
return 0;
}
Also res should also be declared char res;
So basically after the calculation the program prompts the user if they want to quit the program and the user inputs a character ('y' or 'n') and if the user puts a number or letter that is not 'y' or 'n' then the program will keep prompting the user until they input one of the characters.
The issue I'm running into is that the program will keep looping and prompting the user even if 'y' or 'n' is inputted. When I try fflush(stdin) it still doesn't work
I want to know how to loop the statement again if the user does not input one of the options and when they do input it properly, how to get the code inside the "do while" loop to repeat. Preferably without having to copy and paste the whole bloc again.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");
scanf("%f", &x);
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
scanf("%f", &t);
}
fflush(stdin);
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
scanf() will not throw away the newline character '\n' in the input buffer unless your format string is set to discard it. In your code, after entering input for your floats and pressing Enter, the newline is still in the buffer. So for the code that prompts Y\N, use this format string to ignore the newline
scanf(" %c",&d);
You can remove the fflush() calls if you do that. In your case, it looks like your loop conditionals are wrong though.
This line
while (d != 'y' || d != 'n')
is wrong.
Think of it like this:
The loop runs if d is NOT 'y' OR d is NOT 'n'
Now imagine you put in 'y'
d is 'y'. The loop runs if d is NOT 'y' OR d is NOT 'n'. Is d != 'y'? No. Is d != 'n'? Yes. Therefore the loop must run.
You need to use &&
while (d != 'y' && d != 'n')
Also, scanf doesn't throw away the newline so add a space for all your scanfs.
scanf("%c", &d); //change to scanf(" %c", &d);
Look in this part-
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
you are using whiletwice, i think you will wish to have a single while condition over here.. also if you are terminating while, then be sure there is a doinvolved.
Here is code which I think is right since you have many problems so i just have changed a lot :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");//delete the repeat scanf
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
}
fflush(stdin);
sum=0;//no initalization
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while ((d != 'y' )&& (d != 'n'))//this logical expression is the right way
{
scanf("%c", &d);
fflush(stdin);
printf("\n****************************************");//I change the pos of print to avoid double printing
printf("\nDo you wish to quit? (y/n): ");
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
ps:for your calculate part of cos I'm not sure about the correctness while runing:)
I just don't understand why this Yes/No loop will not work. Any suggestions? Given the input is "Y". I just want it to run the loop, then ask for Y or N again. If Y, print success, if N, print a good bye statement. What's the reason?
int main(){
char answer;
printf("\nWould you like to play? Enter Y or N: \n", answer);
scanf("%c", &answer);
printf("\n answer is %c");
while (answer == 'Y'){
printf("Success!");
printf("\nDo you want to play again? Y or N: \n");
scanf("%c", &answer);
}
printf("GoodBye!");
return 0;
}
Change the second scanf to:
scanf(" %c", &answer);
// ^
The problem is, when you enter Y and press ENTER, the new line is still in the input buffer, adding a space before %c could consume it.
fixed the various issues
#include <stdio.h>
int main(){
char answer;
printf("\nWould you like to play? Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n answer is %c\n", answer);
while (answer == 'Y'){
printf("Success!");
printf("\nDo you want to play again? Y or N: \n");
scanf(" %c", &answer);
printf("\n answer is %c\n", answer);
}
printf("GoodBye!");
return 0;
}
You can reduce the repetition in your code a bit, and check the result of scanf() (as you should) by writing:
int main(void)
{
char answer;
printf("Would you like to play? Enter Y or N: ");
while (scanf(" %c", &answer) == 1 && answer == 'Y')
{
printf("Answer is %c\n", answer);
printf("Success!\n");
printf("Do you want to play again? Y or N: ");
}
printf("GoodBye!\n");
return 0;
}
The first printf() lost the unused argument answer; the second printf() collected the necessary second argument, answer. Except for prompts, it is generally best to end printing operations with a newline (rather than use a newline at the start). Prompts will generally be flushed by the C library before the input from stdin is read, so you don't need the newline at the end of those.
Since printf() returns the number of characters it prints, you can use it in conditions too:
int main(void)
{
char answer;
printf("Would you like to play? Enter Y or N: ");
while (scanf(" %c", &answer) == 1 &&
printf("Answer is %c\n", answer) > 0 &&
answer == 'Y')
{
printf("Success!\n");
printf("Do you want to play again? Y or N: ");
}
printf("GoodBye!\n");
return 0;
}
This always echoes the answer, even if the answer was not Y and the loop exits.