C while showing two times before stop - c

This is the called Function:
int onBattle(int level,char nomeheroi[20])
{
const char *monsternames[4][3] = {
{"Rat","Bat","Spider"},
{"Goblin","Orc","Dwarf"},
{"Dragon","Lich","Banshee"},
{"Demon","Hydra","Giant Spider"}
};
//printf("monster hp:%f , player hp:%f, player name:%s ",globalvar.monterhp, globalvar.playerhp,nomeheroi);
char opcaobattle;
rndMonster(level);
while((globalvar.monterhp > 0) || (globalvar.playerhp > 0)){
printf("Monster name:%s\n",monsternames[globalvar.monstercatego][globalvar.monsternivel]);
printf("Monster Life:%f\n",globalvar.monterhp);
printf("------------------------------------------\n");
printf("----------------BattleGround--------------\n");
printf("------------------------------------------\n");
printf("Player name:%s\n", nomeheroi);
printf("Player life:%f\n", globalvar.playerhp);
printf("----------------------------------------\n");
printf("------------------Menu------------------\n");
printf("----------------------------------------\n");
printf("A - Attack\n");
printf("D - Defend\n");
scanf("%c",&opcaobattle);
switch(opcaobattle)
{
case 'a':
danoPMonster();
break;
case 'd':
break;
}
}
if(globalvar.monterhp <= 0)
{
return 0;
}
else if(globalvar.playerhp <= 0)
{
return 1;
}
}
This is what happen:
I dont any problem with this code to show two times before stop on Scanf, i tried Do While too and the same thing happens any help?
ps: that globalvar is a global struct and yes there is a value

scanf("%c",&opcaobattle);
I suggest adding a space to the conversion specifier to make sure it isn't using a left-over newline character in the stream.
scanf(" %c",&opcaobattle);
It might be good to have a default case for the switch, too:
default:
printf("Please enter one of the available commands.\n");

Related

scanf and switch statement debug

All the cases work except the switch 'a' case. The a case runs the insert method below. Any help would be appreciated, thanks. printf statements inside the switch statement don't work.
void insert() {
char name;
printf("enter your name");
scanf("%c", &name);
for(int i = 0; i < LENGTH; i++){
if (!Thesame(names[1], name) == 0 && counter != LENGTH && strlen(name) <= MAX){
for(int j = 0; j < LENGTH; j++){
strcpy(names[counter],name);
}
}
else{
printf("error");
}
}
```
int main() {
while (1) {
char input;
printf("Type in 'a' be added to the system \n");
printf("Type in 'n' to print next patient and remove from
waitlist \n");
printf("Type in 'l' to list the patients on the waitlist \n");
printf("Type in 'q' to quit the program \n");
scanf("%c", &input);
switch (input) {
case 'a':
insert();
break;
case 'n':
next();
break;
case 'l':
print();
break;
case 'q':
return 0;
}
}
}
char name;: name can contain only a single character. So when you type for example: cuq, name will contain c, then insert does whatever with name and then returns to main. Then in main scanf("%c", &input) will read the remaining characters from the input buffer ('u' and 'q') and because of case 'q': the programs stops. Use a debugger or put some printfs at strategic places in your code to see what happens.
You want a string here and you probably want something like this in insert:
char name[100];
printf("enter your name: ");
scanf("%s", name);
...
You also probably need to change the Thesame function.

When the main() function is called back the program is terminated. Is there a way I can fix this?

I have to write a c program to manage the reservations. When I call back the main function the program gets terminated without continuing. How can I fix this error? ( I haven't written the whole program)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i, j, day, x;
char session[10];
int array[2][5] = {{0,0,1,0,1},{1,1,0,0,0}};
char response,ans,choice;
printf("**************** WELCOME TO NAT RESERVATION SYSTEM ****************");
printf("\n\nCHOOSE WHAT TO DO");
printf("\n\n\t\tA.\t\tBOOK THE THEATER");
printf("\n\t\tB.\t\tCHECK RESERRVATIONS");
printf("\n\t\tC.\t\tREMOVE RESERVATIONS");
printf("\n\t\tD.\t\tCALCULATE INCOME");
printf("\n\t\tE.\t\tEXIT");
printf("\n\nYOUR RESPONSE\t\t: ");
scanf("%c",&response);
switch (response){
case 'A': printf("\n\nBOOK THE THEATER"); break;
case 'B': printf("\n\nCHECK RESERRVATIONS"); break;
case 'C': printf("\n\nREMOVE RESERVATIONS"); break;
case 'D': printf("\n\nCALCULATE INCOME"); break;
case 'E': printf("\n\nEXIT"); break;
}
if (response == 'A'){
printf("\n\nCHOOSE A DAY : ");
scanf("%d",&day);
j = day -1;
printf("YOUR SESSION : ");
scanf("%c",session);
fgets(session,10,stdin);
if(strcmp(session,"MORNING")){
i = 0;
}else if(strcmp(session,"AFTERNOON")){
i = 1;
}else{
printf("PLEASE ENTER MORNING OR AFTERNOON");
}
if(array[i][j] == 0){
printf("\n\nTHE SESSION IS AVAILABLE.\nDO YOU WANT TO CONFIRM THE BOOKING?(Y/N) : ");
scanf("%c",&ans);
I want to direct the program to print the main menu. So I called back the main() function here.
if(ans == 'Y' || ans == 'y'){
array[i][j] = 1;
printf("\nYOUR BOOKING WAS SUCCESSFUL!\n\n");
main();
}
}else if(array[i][j] == 1){
printf("\n\nTHE SESSION IS NOT AVAILABLE.");
printf("DO YOU WANT TO TRY ANOTHER SESSION?(Y/N): ");
scanf("%c",&ans);
if(ans == 'Y' || ans == 'y'){
main();
}else if(ans == 'N' || ans == 'n'){
printf("THANK YOU! HAVE A NICE DAY!");
exit(0);
}
}
}
}
I tried to use a while loop. I don't know what to put inside the brackets. Please help me. I'm new to C programming as I learned most of them online.
while(1){
printf("**************** WELCOME TO NAT RESERVATION SYSTEM ****************");
printf("\n\nCHOOSE WHAT TO DO");
printf("\n\n\t\tA.\t\tBOOK THE THEATER");
printf("\n\t\tB.\t\tCHECK RESERRVATIONS");
printf("\n\t\tC.\t\tREMOVE RESERVATIONS");
printf("\n\t\tD.\t\tCALCULATE INCOME");
printf("\n\t\tE.\t\tEXIT");
printf("\n\nYOUR RESPONSE\t\t: ");
scanf("%c",&response);
switch (response){
case 'A': printf("\n\nBOOK THE THEATER"); break;
case 'B': printf("\n\nCHECK RESERRVATIONS"); break;
case 'C': printf("\n\nREMOVE RESERVATIONS"); break;
case 'D': printf("\n\nCALCULATE INCOME"); break;
case 'E': printf("\n\nEXIT"); break;
}
if (response == 'A'){
printf("\n\nCHOOSE A DAY : ");
scanf("%d",&day);
j = day -1;
printf("YOUR SESSION : ");
scanf("%c",session);
fgets(session,10,stdin);
if(strcmp(session,"MORNING")){
i = 0;
}else if(strcmp(session,"AFTERNOON")){
i = 1;
}else{
printf("PLEASE ENTER MORNING OR AFTERNOON");
}
if(array[i][j] == 0){
printf("\n\nTHE SESSION IS AVAILABLE.\nDO YOU WANT TO CONFIRM THE BOOKING?(Y/N) : ");
scanf("%c",&ans);
if(ans == 'Y' || ans == 'y'){
array[i][j] = 1;
printf("\nYOUR BOOKING WAS SUCCESSFUL!\n\n");
continue;
main();
}
}
if(array[i][j] == 1){
printf("\n\nTHE SESSION IS NOT AVAILABLE.");
printf("DO YOU WANT TO TRY ANOTHER SESSION?(Y/N): ");
scanf("%c",&ans);
if(ans == 'Y' || ans == 'y'){
continue;
main();
}else if(ans == 'N' || ans == 'n'){
printf("THANK YOU! HAVE A NICE DAY!");
exit(0);
}
}
}
Your original program without while and continue seems to work fine if you use scanf with the format string " %c", that is insert a blank space before the percentage sign. This makes the program skip leading white space. Without the leading space in the format string the newline characters in the input will not be skipped over.
NOTE: It is also better to print a newline at the end of a string. If I choose B, for instance, the program output does not end with a newline so on a non-Windows machine the command prompt (in my case a dollar sign) is displayed on the same line as the output:
CHECK RESERRVATIONS$

Finding Items in Struct and edit them

i have a problem in my code (Case 2), I try to get the position of the item what I get from the scanf() but when I try to get the position it give me a complete random number like 537890.
I can't figure out why my code do that, because the max size of my struct ist 200.
I'm not sure if its because I tried to do &find==wh[a]->artikel
int main() {
struct managementtool {
char artikel[200];
int anzahl;
};
//wh = warehouse
struct managementtool **wh = malloc(200 * sizeof(struct managementtool *));
for (int i = 0; i < 200; i++) {
wh[i] = malloc(sizeof(struct managementtool));
}
printf("Welcome to Warehouse Management 97\n\n\nWhat do you want to do ?\n");
int x,v,f,i,exit,all,end,a,b;
char ques,find, nu1;
do {
i=0;
printf("\n(1)Add article\n(2)Edit article.\n(3)Search entry.\n(4)Show stock.\n(5)Exit\n");
scanf("%x",&x);
switch (x) {
case 1://add
do {
printf("\nEnter the product name: ");
scanf("%s", wh[f]->artikel);
printf("\nAmount of products: ");
scanf("%i", &wh[f]->anzahl);
printf("\n\nAdd another product ? (Y/N)");
// add a space before % to skip leading whitespace
scanf(" %c", &ques);
f++;
switch (ques) {
case 'Y':
v++;
break;
case 'N':
end = 1;
v = 0;
break;
default:
printf("Wrong entry\n");
break;
}
} while (end != 1);
if (v >= 2) {
printf("Product added successfully\n\n");
}else {
printf("Products have been successfully added\n\n");
}
break;
case 2://edit
printf("Which article do you want to edit?");
fflush(stdin);
scanf("%s", &find);
for (a=0;a<f;a++) {
if (&find==wh[a]->artikel) {
b=a;
}
}
if (b==0) {
printf("Article not found");
}
printf("f: %i, b:%i",f,b);
puts(wh[b]->artikel);
printf("Amount: %d\n", wh[b]->anzahl);
break;
case 3://search
break;
case 4://Spam-it
while (i<f) {
printf("\nProduct number %i\n", i+1);
printf("Name: ");
puts(wh[i]->artikel);
printf("Amount: %d\n", wh[i]->anzahl);
i++;
}
printf("\nTotal amount of Items: %i", all);
break;
case 5://go away
printf("Goodbye :)");
exit=1;
break;
default://well
printf("Wrong Input\n");
break;
}
all=0;
while (i<f) {
all += wh[i]->anzahl;
i++;
}
} while (exit==0);
}
In C you need to use strcmp instead of using == to compare strings. You should also use fgets instead of scanf it will make your life easier, you don't have to worry about trying to flush. Example : fgets( my_string_buffer, number_of_char_maximum_to_read , stdin ) . Example for strcmp : if(! strcmp( string1 , string2) , strcmp returns 0 if they are identical.

Repeat the Program Prompt

The current problem is with the Evaluate another interval (Y/N)? prompt. Let's say I run the program 4 times; in order to end it, it requires me to type N 4 times.
int main() {
int trap, test;
double low, hi;
char repeat, c;
//Gather End Points
do {
printf("Enter endpoints of interval to be integrated (low hi): ");
test = scanf("%lf %lf", &low, &hi);
if (test != 2) {
printf("Error: Improperly formatted input\n");
while((c = getchar()) != '\n' && c != EOF); //Discard extra characters
} else
if (low > hi)
printf("Error: low must be < hi\n");
} while ((test != 2 || low > hi));
//Gather amount of triangles
do {
printf("Enter number of trapezoids to be used: ");
test = scanf("%d", &trap);
if (test != 1) {
printf("Error: Improperly formated input\n");
while((c = getchar()) != '\n' && c != EOF); //Discard extra characters
} else
if (trap < 1)
printf("Error: numT must be >= 1\n");
} while ((trap < 1 || test != 1));
//Output integrate
printf("Using %d trapezoids, integral between %lf and %lf is %lf",
trap, low, hi, integrate(low, hi, trap));
//Prompt user for another time
while (1) {
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat) {
case 'Y':
main();
case 'y':
main();
case 'N':
return 0;
case 'n':
return 0;
default:
printf("Error: must enter Y or N");
}
}
return 0;
}
I expect it so that no matter what run of the program I'm on it will close when I type one N.
There are many ways to achieve what you want but calling main recursively is not a good idea.
A pretty simple way to change your program is to add an additional while(1) level. Something like:
int main(void)
{
char repeat;
while(1){ // Outer while to keep the program running
printf("running program\n");
// Put your program here
printf("program done\n");
repeat = '?';
while(repeat != 'y' && repeat != 'Y'){ // Repeat until input is 'Y' or 'y'
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat){
case 'Y':
case 'y':
break;
case 'N':
case 'n':
return 0; // Stop if input is 'n' or 'N'
default:
printf("Error: must enter Y or N");
}
}
}
return 0; // This will never be reached
}
Another way (a simpler way, IMO) is to put the code where you ask the user into a function that you call from main. Like:
int continueProg()
{
char repeat = '?';
while(1){
printf("\nEvaluate another interval (Y/N)? ");
scanf(" %c", &repeat);
switch (repeat){
case 'Y':
case 'y':
return 1;;
case 'N':
case 'n':
return 0;
default:
printf("Error: must enter Y or N");
}
}
}
int main(void)
{
do {
printf("running program\n");
// Put your program here
printf("program done\n");
} while(continueProg());
return 0;
}
BTW: Take a look at getchar instead of using scanf
There are multiple problems in your program:
You test the return value of scanf() when reading the user's answer to the prompts, and you clear the pending input correctly, but you do not handle the potential end of file, leading to endless loops.
c must be defined as int to accommodate for all values returned by getchar(): 256 values of type unsigned char and the special value EOF.
You can main() recursively to repeat the program's action requiring multiple N answers. You should instead add an outer loop and exit from it upon a N answer or an end of file condition.
Here is a modified version:
#include <stdio.h>
double integrate(double low, double hi, int trap) {
...
}
int flush_line(void) {
// Consume the pending input and return `'\n`` or `EOF`
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
return c;
}
int main() {
// Main program loop
for (;;) {
int trap, test;
double low, hi;
char repeat;
//Gather End Points
for (;;) {
printf("Enter endpoints of interval to be integrated (low hi): ");
test = scanf("%lf %lf", &low, &hi);
if (test == EOF)
return 1;
if (test != 2) {
printf("Error: Improperly formatted input\n");
if (flush_line() == EOF)
return 1;
continue; // ask again
}
if (low > hi) {
printf("Error: low must be < hi\n");
continue;
}
break; // input is valid
}
//Gather amount of triangles
for (;;) {
printf("Enter number of trapezoids to be used: ");
test = scanf("%d", &trap);
if (test == EOF)
return 1;
if (test != 1) {
printf("Error: Improperly formated input\n");
if (flush_line() == EOF)
return 1;
continue;
}
if (trap < 1) {
printf("Error: numT must be >= 1\n");
continue;
}
break;
}
//Output integrate
printf("Using %d trapezoids, integral between %lf and %lf is %lf\n",
trap, low, hi, integrate(low, hi, trap));
//Prompt user for another time
for (;;) {
printf("\nEvaluate another interval (Y/N)? ");
if (scanf(" %c", &repeat) != 1)
return 1; // unexpected end of file
switch (repeat) {
case 'Y':
case 'y':
break;
case 'N':
case 'n':
return 0;
default:
printf("Error: must enter Y or N\n");
if (flush_line() == EOF)
return 1;
continue;
}
break;
}
}
}

Continue loop not working correctly

I have two continue loops in the below program- each time when a user enters 'X' or 'x', the program is supposed to again ask the user for input, ie the program is supposed to keep working normally. However, in my program, on entering X/x, it terminates.
I would really appreciate any suggestions as to why this is happening!
#include<stdio.h>
int main(int argc, char const *argv[])
{
char card_name[3];
int count = 0;
while (card_name[0] != 'X')
{
printf("\n Enter the card name\n");
scanf("%2s", card_name);
int val = 0;
switch (card_name[0])
{
case 'K':
case 'Q':
case 'J': val = 10;
break;
case 'A': val = 11;
break;
case 'x':
case 'X':
printf("\n Game ended, thanks for playing!!!\n");
printf("\n New Game begins!!!\n");
continue;
default: val = atoi(card_name);
//break;
if ((val < 1) || (val > 10))
{
printf("\n Incorrect card name entered! Please try again!\n");
continue;
}
}
printf("\n The current card value is:%i\n", val);
//Card counting
if ((val > 2) && (val < 7))
{
count++;
printf("\n The count has gone up\n");
}
else if (val == 10)
{
count--;
printf("\n The count has gone down\n");
}
printf("\n The current card count is %i\n", count );
}
/* code */
return 0;
}
If you enter an uppercase X, your continue goes back to the loop condition;
while(card_name[0]!='X')
...where the value is X and it promptly exits.
Change:
case 'x':
case 'X':
printf("\n Game ended, thanks for playing!!!\n");
printf("\n New Game begins!!!\n");
continue;
to:
case 'x':
case 'X':
printf("\n Game ended, thanks for playing!!!\n");
printf("\n New Game begins!!!\n");
*card_name = '\0';
continue;

Resources