I'm working on a small project right now that allows a user to choose an array editing function from a switch statement. Unfortunately, I coded it poorly (I can't make the switch menu its own function at this point, it is part of main().) I only bring this up to prevent suggestions involving calling a menu function. I also cannot use main() recursion because I take user input for the array and do not want to replace the existing values.
The code below is supposed to take user input to decide whether to exit the program or to re-open the selection screen and
char restart = 'y';
do {
printf("Would you like to try a different function? (Y/N): ");
restart = getchar();
restart = getchar();
system("clear");
goto START; // "START" is the label for my main selection screen function.
} while ( restart == 'Y' || restart == 'y');
system("clear");
printf("Okay, thank you!\n\n");
for (i = 3; i > 0; i++) {
printf("Exiting in %d seconds...", &i);
sleep(1);
}
(At the end of main() I included an exit function.)
I have two questions:
How can I detect if the user inputs an invalid character? (Not n, N, y, Y) I was initially going to build this with if-else statements, but realized that was ineffective. However, now I no longer know how to work with the do-while loop to detect these inputs.
This code simply doesn't work. What'd I do wrong? When inputting y or Y, the loop never exits. Should I embed the do-while loop in a while loop utilizing breaks?
My only theories right now (as a baby C programmer) are that labels don't work with this method or that I have no real way to break from the loop.
Thank you!
Related
For starters, I am new to C and programming in general. I have more experience with PowerShell and bash scripting, so apologies in advance for errors with headers, indentation, syntax, etc. Anyway, I'm trying to complete this program for a class, but I've had some trouble with one particular section, so I'm looking for some guidance as I'm pretty lost right now.
To provide some background: I'm supposed to allow a user to enter a user code between 6 and 10. This code uniquely identifies the user, who would then be asked for input for several other integer values, which would be totaled and averaged at the end. However, the user must be able to start the program again and enter another number (between 6 and 10); the user must then go through the previous process again to finish the program.
My problem is I cannot use if statements, break, continue, exit, abort or goto; I must use a do while loop to figure out when the user is done entering input; and I must provide error messages for when the user enters the wrong input, prompting them to enter it again.
With what I've posted below, I cannot figure out how to give the user an option to continue and/or exit without using if, break, continue, etc and while also prompting for error messages. I'm probably overthinking something but if anyone can provide some insight I would greatly appreciate it.
#include<stdio.h>
main()
{
int usercode; /* setting variables for user code */
do
{
printf ("Please enter your user code: ");
scanf("%1d", secid); /* user must input 1 digit code */
} while(secid >= 6 || secid <= 10); /* code must be between numbers 6 and 10 */
}
You don't use the loop for logging in, you use it for the other input
pseudocode:
get user id
do {
get a value
} while (value is not pause or quit)
The while at the end of a do while is like a repeated if. If will be asked again and again until it is false. Note that the block of do while will be executed at least once, because the cycle test is executed after the content of the block. You need int secid instead of int usercode. Inside the do while you need another do while to read the data and to calculate sum and avg in the process.
The code you are looking for looks like this:
#include<stdio.h>
int main(int argc, char **argv){
int secid = -1;
do {
printf("Please enter your user code: ");
scanf("%1d", &secid);
} while((secid < 6 || secid > 10) && printf("Error\n"));
printf("The user code was %d", secid);
return 0;
}
This question already has an answer here:
Read user input until ESC is pressed in C
(1 answer)
Closed 6 years ago.
let say i'm in an infinite while loop and i want the user to enter the data in integer form. Then the data will be passed to another function for some other purpose this process will keep continuing until the user input esc in the place of data and i want the loop to break at that point. how should i do that?
while(1)
{
printf("enter the data that need to entered\npress esc to exit\n");
scanf("%d",&n);
function(n);
}
i tried to use if-else but if i put the ascii value of esc as the data input it exits the loop which i don't want to happen?
As dingrite wrote in his other answer:
Your best bet is to create a custom "GetAsyncKeyState" function that will use #IFDEF for windows and linux to choose the appropriate GetAsyncKeyState() or equivalent.
No other way exists to achieve the desired result, the cin approach has its problems - such as the application must be in focus.
Take a look at this question: C++: execute a while loop until a key is pressed e.g. Esc?
Or you can try with this example found on other page
#include <stdio.h>
int main (void)
{
int c;
while (1) {
c = getchar(); // Get one character from the input
if (c == 27) { break; } // Exit the loop if we receive ESC
putchar(c); // Put the character to the output
}
return 0;
}
Hope this helps.
I am currently trying to make code for a calculator that will calculate the area of a circle, cube, or square, depending on which integer the user enters in the beginning, then prompt for the measurements, etc. I want the user to choose between 1, 2, or 3.
My current code:
#include <stdio.h>
#include <math.h>
int main(void){
int shape;
printf("\nArea calculation\n(1) Square\n(2) Cube \n(3) Circle \nPlease make a selection");
scanf("%d", &shape);
else{
printf("\nIncorrect Choice");
}
return 0;
}
My question is:
How can I make an error message pop up if they haven't entered that info?
How I can make it loop and ask the same question again if they enter something other than 1, 2,3.
How do I make it so if the user enters something line: 99 then the program shuts off?
You need to read and probably do a few c tutorials before you try to do this. These will get you started toward learning how to (1) print error output, (2) handle input, and (3) manage program control, which are the three things you seemed to ask about. There are a lot of ways to do this.
For error printing, look up stdout and stderr. A common strategy when learning might be using the function fprintf to write to standard error.
fprintf(stderr, "Error: incorrect value inputted. Please enter 1, 2, or 3.\n");
For input handling, you should google examples. Your scanf statement should end in a semicolon, not a colon. Statements in C end in a semicolon. Then you need some control flow to see what they entered and do something different based on that. A switch statement may make sense where, as here, you have a small number of options to deal with.
/* put in a function so we can call it from main() multiple times. */
int myFunction() {
scanf("%d", &shape);
switch(shape) {
case 1:
/* do stuff */
break;
case 2:
/* do stuff */
break;
case 99:
return 99;
default:
fprintf(stderr, "Incorrect Choice");
}
}
Program Control. Finally, you want to be able to call this again if they fail. So put it in a function, and call that function from main.
int main() {
/* this empty while loop will call myFunction() forever, */
/* or until it returns a 99 because someone quit. */
while(myFunction() != 99) ;
}
This is a bit inelegant but should get you started. Again, you really, really want to start looking at tutorials on learning the language.
Build succeeds. If I open the output window, it reads:
Program ended with exit code: 0
But my program is such that this shouldn't be possible, without first having taken user input, done some stuff, and taken another user input, all in int main().
The first thing int main() does is loop through taking input for p, until the input is one (of two) desired options. So there's no way it should be able to exit immediately - it initialises p=0 and doesn't exit a while loop until p is 1 or 2.
Is there some hidden error that has allowed the build to succeed without it actually.. succeeding?
int main(){
//vars
while (TRUE){
//play computer or human?
while (!(p == 1 || p == 2)) {
printf("Single player or two player? (1/2): ");
scanf("%d", &p);
}
if (p==1) {
//play computer
}
else {
//snip
}
printf("%s won the game! Play again?", winner);
scanf("%s", playagain);
if (strncmp(playagain,"no",2)==0){
break;
}
}
return 0;
}
Print out what uppercase TRUE is defined as. I have seen some ambitious but inexperienced folks do weird things with it. You might not even be getting into your main while loop.
printf("TRUE is %d\n",TRUE);
If this is nonzero, then your problem is elsewhere.
I am writing a game code in C which involves display of numbers with a time gap entered by the user.
srand ( time(NULL) ); //this avoids generating the same random number everytime
start:
mySleep(userdelay);
printf("\n\n\a\t%d",rand()%90); //prints random numbers with the time delay entered by the user.
goto start;
So I just wanted to know how to pause this loop with user input like "Press 1 to pause" and resume the same loop with user input like "Press 2 to resume".
Thanx in advance!
I'm not sure this may be the best way, but it could be one working way. Try using a while loop in your command console:
int main(){
int i;
scanf("%d",&i)
switch(i){
case 1: while(i != 2){
sleep(1); //or define duration by a variable if time should be "dynamic"
scanf("%d",&i);
break;
}
}
}
I hope you get an idea of the idea.
EDIT:
If you want the user to input data until "exit key" a while loop is much bether than goto. If you are not familiar with switch(){} i advice you to take a look here.