#include <stdio.h>
#include <stdlib.h>
struct cal {
int date;
int time;
int importance;
char title[256];
char description[256];
};
int count;
void change_Cal (struct cal *calendar) {
for (long long int i = 0; i < count; i++) {
int year = 0, month = 0, day = 0;
year = calendar[i].date / 10000;
month = (calendar[i].date - 10000 * year) / 100;
day = calendar[i].date % 100;
printf("%04d.%02d.%02d. ", year, month, day);
int hour, min;
hour = calendar[i].time / 100;
min = calendar[i].time % 100;
printf("%02d:%02d %d %s %s\n",hour,min,calendar[i].importance, calendar[i].title, calendar[i].description);
}
}
int main() {
struct cal *calendar;
//struct cal calendar[1024] = { 0, };
printf("please input the number of the calender.\n>");
scanf("%d", &count);
calendar = (struct cal *)malloc(sizeof(struct cal)*count);
calendar = (struct cal *)calloc(count, sizeof(struct cal));
printf("input calendars.\n");
for (int i = 0; i < count; i++) {
printf(">");
scanf("%d %d %d %c %c", &calendar[i].date, &calendar[i].time, &calendar[i].importance, calendar[i].title, calendar[i].description);
printf("\n");
}
change_Cal(calendar);
}
The
printf("%02d:%02d %d %s %s\n",hour,min,calendar[i].importance, calendar[i].title, calendar[i].description);
part is not working.
Some data is corrupted too.
Input : 20180927 0900 0 iiii
Output: 2018.09.27. 09:00 0 i i
Process returned 0 (0x0) execution time : 12.588 s
I think some pointers are the problem.
What's the problem?
You use this
scanf("%d %d %d %c %c", &calendar[i].date, &calendar[i].time, &calendar[i].importance, calendar[i].title, calendar[i].description);
to read this
20180927 0900 0 iiii
^ ^ ^ ^^
%d %d %d cc
So you get a number, a number, a number, a character ('i') and a character ('i').
Did you notice the risk of confusing a number with a leading 0 with an octal number?
The blank in the format string between the two expected characters, will be parsed as "take any present whitespace" which for "iiii" is "no whitespace".
You will leave in the input stream "ii\n"; which will confuse the next attempt to scan a number and make it fail. I.e. the return value of the next scan-attempt (which you ignore in your code) will be 0, while it should be 5.
To fix read about all the things that can go wrong with complex input scanning via scanf:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
Then change to something which can read strings instead of character, but probably not scanf().
Related
How do I terminate the while loop without needing the user to enter q twice?
I think I have an input buffer somewhere, but I am not sure where my problem is.
#include <stdio.h>
#include <string.h>
int main(void)
{
int Length, fLength, iLength;
char sObject [25];
printf("Enter object and object length in inches (q to quit); \n");
while (scanf("%24s %d", sObject, &Length) > 1) {
fLength = Length / 12;
iLength = Length % 12;
printf("The length of %s is %d foot %d inches\n", sObject, fLength, iLength);
printf("Enter object and object length in inches (q to quit); \n");
}
return 0;
}
Here is an example of my output.
Enter object and object length in inches (q to quit);
bat 100
The length of bat is 8 foot 4 inches
Enter object and object length in inches (q to quit);
q
q
The first q matches the %24s conversion specification, the second q causes the %d to fail, hence scanf() returns 1 and the loop is exited.
You should read a full line of input at a time, test for the exit command and attempt to convert with sscanf() otherwise
Also note that the split into feet and inches is incorrect: you should compute inches before dividing fLength. Using 2 extra variables is more readable and less error prone.
Here is a corrected version:
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[100];
char object[25];
int length;
for (;;) {
printf("Enter object and object length in inches (q to quit):\n");
if (!fgets(buf, sizeof buf, stdin)) {
/* end of file or read error */
break;
}
if (!strcmp(buf, "q\n")) {
/* user typed q enter */
break;
}
if (sscanf(buf, "%24s %d", object, &length) == 2) {
int feet = length / 12;
int inches = length % 12;
printf("The length of %s is %d foot %d inches\n",
object, feet, inches);
} else {
printf("invalid input: %s\n", buf);
}
}
return 0;
}
If I have understood correctly then rewrite the while statement for example the following way
while (scanf("%24s", sObject) == 1 && strcmp(sObject, "q") != 0 && scanf("%d", &Length) == 1) {
I'm stuck on trying to figure out how to take a multiple candidate data from a loop and figure out a winner from them by stating their name, ID, and total percent of votes within the same function. I also need to return the winning candidates ID from the function. For example: candidate 1 - is named Stevens with ID 13.07 and total votes of 1500, candidate 2 - is named George with ID 17.49 and total votes of 2000. I need to output the winner which is George with ID 17.49 and his percent of the total 3500 votes. This is what I have so far but I'm new to programming and have no idea how to figure this out. Any help would be greatly appreciated!
float CandidateData(int N, int X) {
char candName[21];
int i;
double candID;
int candVotes;
int voteSum;
int j = 0;
double max = 0;
double first;
for (i = 0; i < N; i++) { //N is the number of candidates
printf("Enter candidates name (20 characters max): ");
scanf("%s", &candName);
printf("Candidate name: %s\n\n", candName);
printf("Enter candidate ID (float 01.01-52.99): ");
candID = CandidateID(52.99);
printf("Candidate ID is: %g\n\n", candID);
printf("Enter %d precinct votes (int 1-1000): ", X);
voteSum = 0;
for (j = 0; j < X; j++) { //X is number of precincts
candVotes = NumberOfCandidatesAndPrecincts(1000);
printf("Precinct #%d = %d\n", j + 1, candVotes);
voteSum = voteSum + candVotes;
}
printf("Total candidate votes = %d\n", voteSum);
printf("Average votes for county = %d\n\n", voteSum / X);
if (voteSum > max) {
max = voteSum;
}
}
printf("The winning candidate is %s with ID %g with %d% of total votes", candName, candID, )
return (candID);
}
I see few mistakes in your code.
First of all, it should be :
scanf("%s", candName);
not
scanf("%s", &candName);
Because candName is already the address of the first element of the array.
Another issue, suppose a user types Whoever President for candName. Then try this:
printf("Candidate name: %s\n\n", candName);
You will see that only Whoever is printed because scanf("%s",candName) takes input until a white space comes. It can be a blank space (' '), new line (\n) or tab (\t).
Instead, I strongly suggest you to use fgets.
fgets (candName, 21, stdin);
where 21 is the maximum buffer length that you want to have.
Now, you can print candName with printf and observe that fgets puts extra new line ('\n') at the end of your string. You can easily remove it by:
if ((strlen(candName) > 0) && (candName[strlen (candName) - 1] == '\n')){
candName[strlen (candName) - 1] = '\0';}
Keep in mind that using fgets and scanf together is problematic because scanf function leaves \n in the input buffer, after fgets reads input from buffer, you will encounter unexpected results. Use getchar(); after each scanf. It consumes \n. The problem disappears!
The next mistake you made is return_type of CandidateData function. Its return_type is float but type of candID variable is double so make a change for just one of them. In your task, it is sufficient to use float type for candID.
There are also some typos in the last printf function. It should be:
printf("The winning candidate is %s with ID %f with %d of total votes", candName, candID, voteSum);
Let's come to your question. To store the candidate who takes maximum vote, you can declare a struct and fill related fields when number of votes of a candidate exceeds current max value.
I add the final code:
#include <stdio.h>
#include <string.h>
struct President{
char candName[21];
float candID;
int candVotes;
};
float CandidateData(int N, int X) {
struct President winnerCandidate = {.candVotes = 0};
char candName[21];
float candID;
int candVotes;
int voteSum;
int i,j;
for (i = 0; i < N; i++) { //N is the number of candidates
printf("Enter candidates name (20 characters max): ");
fgets (candName, 21, stdin);
if ((strlen(candName) > 0) && (candName[strlen (candName) - 1] == '\n')){
candName[strlen (candName) - 1] = '\0';}
printf("Candidate name: %s\n", candName);
printf("Enter candidate ID (float 01.01-52.99): ");
scanf("%f",&candID);
getchar();
printf("Candidate ID is: %.2f\n", candID);
voteSum = 0;
printf("Enter %d precinct votes (int 1-1000):\n", X);
for (j = 1; j <= X; j++) { //X is number of precincts
scanf("%d",&candVotes);
getchar();
printf("Precinct #%d = %d\n", j , candVotes);
voteSum = voteSum + candVotes;
}
printf("Total candidate votes = %d\n", voteSum);
printf("Average votes for county = %.3f\n\n", voteSum/(float)X);
if(voteSum > winnerCandidate.candVotes){
winnerCandidate.candVotes = voteSum;
winnerCandidate.candID = candID;
strcpy(winnerCandidate.candName,candName);
}
}
printf("The winning candidate is %s with ID %.2f with %d of total votes", winnerCandidate.candName, winnerCandidate.candID, winnerCandidate.candVotes);
return winnerCandidate.candID;
}
int main(){
float winner_candID = CandidateData(3,2);
printf("\nWinner Candidate ID is: %.3f",winner_candID);
return 0;
}
If you have any question, let me know!
I know this question has been asked before and I am sorry but I cannot find a solution for my code. I am a new student to the C language and my problem is that I am trying to create a while loop that continually asks the user to update the data if they enter non integers. I have looked into the isdigit() function and I think that would work. I just can't seem to make it work for my code, as in whenever I try creating a while loop with isdigit as its condition, I either get a infinite loop, or my isdigit returns values that I was not expecting. I think the problem could be that my scanf() is scanning three integers separated by '/' but I am not sure if that is where the problem is. Any help would be appreciated.
Here is the code in question
#include <stdio.h>
#include <ctype.h>
int calcAge(int a, int b, int c, int d, int e, int f);
int maxHeart(int a);
int heartRangeLow(int a);
int heartRangeHigh(int a);
int main(void) {
int birthMonth = 0, birthDay = 0, birthYear = 0, targetRangeLow = 0;
int month = 0, day = 0, year = 0, age = 0, heartRate = 0, targetRangeHigh = 0;
printf("What is your birthday?(written in MM/DD/YYYY)"
"\nHit Enter after you type it in.\n");
scanf_s("%d/%d/%d", &birthMonth, &birthDay, &birthYear);
printf("What is the date today?(written as MM/DD/YYYY)"
"\nHit Enter after you type it in.\n");
scanf_s("%d/%d/%d", &month, &day, &year);
age = calcAge(birthMonth, birthYear, birthDay, month, day, year);
heartRate = maxHeart(age);
targetRangeLow = heartRangeLow(heartRate);
targetRangeHigh = heartRangeHigh(heartRate);
printf("You are %d years old.\n", age);
printf("Your maximum heart rate is %d beats per minute.\n", heartRate);
printf("Your target-heart-range is %d"
" to %d beats per minute.\n", targetRangeLow, targetRangeHigh);
system("pause");
return 0;
}
int calcAge(int a, int b, int c, int d, int e, int f)
{
int age;
age = ((f * 10000 + d * 100 + e) - (b * 10000 + a * 100 + c)) * .0001;
return age;
}
int maxHeart(int a)
{
int heartRateMax;
heartRateMax = 220 - a;
return heartRateMax;
}
int heartRangeLow(int a)
{
int lowTarget = a * .5;
return lowTarget;
}
int heartRangeHigh(int a)
{
int highTarget = a * .85;
return highTarget;
}
to create a while loop that continually asks the user to update the data if they enter non integers.
Make a helper function.
Read user input with fgets() into a buffer and then parse it for valid input with strtol() or sscanf(), is...(), etc. Return 1, 0, EOF depending on input.
// Untested code
// 1 success
// 0 bad input
// EOF end of file
#define DATE_STR_SIZE 80
int enter_date_mdy(char *prompt, int *m, int *d, int *y) {
if (prompt) {
fputs(prompt, stdout);
fflush(stdout);
}
char buffer[DATE_STR_SIZE];
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
return EOF;
}
int n = 0;
sscanf(buffer, "%d /%d /%d %n", m, d, y, &n);
// If scan incomplete or extra junk at the end ....
if (n == 0 || buffer[n]) {
return 0;
}
// Additional tests as desired ....
if (*m < 1 || *m > 12 || *d < 1 || *d > 31) {
return 0;
}
return 1;
}
Sample use
int count;
do {
count = enter_date_mdy("What is your birthday?(written in MM/DD/YYYY)",
&birthMonth, &birthDay, &birthYear);
if (count == EOF) return(EXIT_FAILURE);
} while (count < 1);
do {
count = enter_date_mdy("What is the date today?(written as MM/DD/YYYY)",
&month, &day, &year);
if (count == EOF) return(EXIT_FAILURE);
} while (count < 1);
Tip: instead of "What is the date today?", research time(), mktime().
What do I need to add to get the output to display to the user? I am not sure what printf statement I need to add to make it work. I know how to display text to the user but not how to display the results of the calculations.
#include <stdio.h>
#define NORMAL_ROD 10
#define SENTINEL 0
int main(void)
{
//Variable declarations
int normal_count = 0;
int normal_total = 0;
int long_count = 0;
int long_total = 0;
int short_count = 0;
int short_total = 0 ;
double normal_average;
double long_average;
double short_average;
double overall_average;
int overall_count =0;
int overall_total= 0;
int rodLength = 1;
printf("Rod Manufacturing Quality Control\n");
while(1)
{
printf("Input Rod Length: ");
scanf("%i", &rodLength);
if(rodLength == SENTINEL) break;
overall_count = overall_count + 1;
overall_total = overall_total + rodLength;
if(rodLength == NORMAL_ROD)
{
normal_count = normal_count + 1;
normal_total = normal_total + rodLength;
}
else if(rodLength > NORMAL_ROD)
{
long_count = long_count +1;
long_total = long_total + rodLength;
}
else
{
short_count = short_count +1;
short_total = short_total = rodLength;
}
}
// Average calcs
normal_average = (double)normal_total / normal_count;
short_average = (double)short_total / short_count;
long_average = (double)long_total / long_count;
overall_average = (double)overall_total / overall_count;
/*
...
...
...
*/
// Print output
printf("Statistics:\n");
printf("Desc Number Total Average\n");
return 0;
}
/*
Output here!
*/
To print the results you can use "format specifiers" like in scanf().
When you use
scanf("%d", &age);
Here %d is format specifier for integer. You can similarly use format specifiers for printf() as well.
For example:
If you have your age stored in an integer variable age then you can print it like this:
printf("Age is: %d",age);
Here printf() prints whatever is inside " "(first Argument) to the monitor. While doing so %d is replaced by the value of age.
So if age is equal to 25, then what will be displayed is as below:
Age is 25
%d is Format specifier for INTERGER variables. Each data type have their own format specifiers.
One more ex:
printf("Age is %d , weight is %d", age, weight);
So basically you need to use format specifier in the printf() statement to print values stored in variables. And if you have your results stored in variables, you can use those variable names with correct format specifiers.
You can google, "format specifiers in C" to find out format specifiers of all data types used in C.
You don't say what number corresponds to each description. Anyway to show a double use printf("%f", doubleValue);
// Print output
printf("Statistics:\n");
printf(" Average %f\n",normalAverage );
Analogously use %s for strings, %c for characters, or %d for integers
printf("%f", normal_average); /*double */
Question : Program that asks the user to enter an item price value and then show how to pay that amount using the smallest number of $ 50,$20, $10,$5, and $1 bills consist.
Example Output:
Enter Price: 187
Enter Amount to pay: 500
Change is : 313
(6)$50 (1)$10 (3)$1
(0)$20 (0)$5
Here's my code: hope you help me , I am having a hard to in knowing the right formula for it..
#include <stdio.h>
#include <conio.h>
#define p printf
#define s scanf
#define g gotoxy
main()
{
clrscr();
int c1,c2,c3,c4,c5;
int price,amount;
float change;
p("Enter Price: ");s("%d",&price);
p("Enter amount: ");s("%d",&amount);
change=amount-price;
p("Change is : %f ",change);
c1=(change/50);
c2=(0);
c3=(change/change);
c4=(0);
c5=(change/change)+2;
g(5,5);p("(%d) Php 50",c1);
g(5,6);p("(%d) Php 20",c2);
g(18,5);p("(%d)Php 10 \t",c3);p("(%d)Php 1",c5);
g(18,6);p("(%d) Php 5 ",c4);
getch();
return 0;
}
You're on the right track:
change should be a int too (that means you should change %f to %d). You would then correctly determine the number of 50's (note that integer division in C truncates). You should look at % (modulus operator) to get the remaining amount of changes after the 50's are dealt with:
Using your example:
change = 313
fifties = 313/50 (6)
change %= 50 (13)
That means set change to the remainder after dividing itself by 50 (change = change % 50)
twenties = change / 20 (0)
change %= 20 (13)
tens = change / 10 (1)
change %= 10 (3)
This should give you the basic idea of the code you need. You just continue this pattern in order of decreasing denomination.
As noted, use better variable names, don't use those defines, and generally stick to one statement per line (add a newline after semi-colons). This will make your code more readable. You're also using more parentheses than needed, but that's not a big deal.
I would suggest define an array which holds the bill denominations, and an initially empty array of bill counts:
int denoms[5] = {50, 20, 10, 5, 1};
int bills[5] = {0, 0, 0, 0, 0};
for(int i =0; i < 5; ++i)
{
bills[i] = /* do something interesting with denoms[i] here */
change = /* more work for you here */
}
/* output answer */
for(int i =0; i < 5; ++i)
{
if (bills[i] > 0)
p("{%d)$%d", bills[i], denoms[i]);
}
p("\n");
for(int i =0; i < 5; ++i)
{
if (bills[i] == 0)
p("{%d)$%d", bills[i], denoms[i]);
}
p("\n");
void changeloop(int* change, int* counter, int amount) {
while (*change > amount) {
(*counter)++;
(*change) -= amount;
}
}
int main() {
clrscr();
int price; printf("Enter Price: "); scanf("%d", &input);
int amount; printf("Enter Amount: "); scanf("%d", &amount);
int change = amount - price;
int fifties, twenties, tens, fives, ones;
fifties = twenties = tens = fives = ones = 0;
changeloop(&change, &fifties, 50);
changeloop(&change, &twenties, 20);
changeloop(&change, &tens, 10);
changeloop(&change, &fives, 5);
changeloop(&change, &ones, 1);
printf("Fifties: %d\n", fifties);
printf("Twenties: %d\n", twenties);
printf("Tens: %d\n", tens);
printf("Fives: %d\n", fives);
printf("Ones: %d\n", ones);
getch();
return;
}
There's work to do, like input validation and error handling. But the basics are here. The code could be refactored to be much more extensible... but meh.