Reputation: 63
I was trying to create a program that runs infinitely until you type "exit". When a user types "donate", the program will prompt "Great! How much?". The program will keep on asking to donate until the donation money is greater than $100 (the target). The program will also have to ask you to "work here", if the user types "work here", the program will display how much has been donated. The issue is when I type "donate" below the target, the program stops after I type in the donation money. The same issue occurs when I type "work here". Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char**argv)
{
int total=0;
int target=100;
char descision[20];
int amount=0;
while(1)
{
printf("***Welcome! Are you looking to donate or do you work here?\n");
scanf("%s", descision);
if(strcmp(descision, "donate") == 0)
{
printf("Great! How much? $");
scanf("%s", amount);
total += amount;
}
else if(strcmp(descision, "work here") == 0)
{
printf("Total donated so far: %d", total);
}
else if(strcmp(descision, "exit"))
{
printf("Bye!!!\n");
exit(0);
}
if(total > target)
{
printf("We already met our target but thanks!");
exit(0);
}
}
return 0;
}
Upvotes: 0
Views: 188
Reputation: 641
printf("***Welcome! Are you looking to donate or do you work here?\n");
scanf("%19[^\n]", &descision[0]); // <-- you need to give base address ampersand of first cell
if(strcmp(descision, "donate") == 0)
{
printf("Great! How much? $");
scanf("%d", &amount); // <-- Give ampersand address character
total += amount;
}
Explanation of scanf("%19s[^\n]", &descision[0]);
Your decision array is of size 20, thus you need the last cell to accommodate '\0'
called null termination which tells printf when string ends. Thus "[19s]"
means read upto 19 characters(will discard any number of characters above 19 count, hence you will avoid issues of overwriting memory beyond the allocation/your expectation) and [^\n]
means read until it finds '\n'
i.e when you hit Enter Key '\n' is generated behind.
Upvotes: 1