Can't nail the problems with this code - c

Ok so I got this thing going here.
I keep getting a few errors.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
//functions called
int get_lmt();
int get_total_trash();
void print_output(int, int);
//why is it void?
int main(void)
{
char hauler[100];
int t_trash=0, lmt=0;
printf("Hello \n What is your name: ");
fflush(stdin);
scanf("%s", &hauler);
t_trash = get_total_trash();
lmt = get_lmt();
printf("Name: %s\n", &hauler);
print_output(lmt, t_trash);
system("pause");
return 0;
}
int get_total_trash()
{
char yn = 'y';
int t_trash = 0, trash=0;
while (yn != 'n')
{
printf("What is your trash: ");
fflush(stdin);
scanf("%i", &trash);
t_trash = trash + t_trash;
printf("Do you have more trash tons? (y or n): ");
fflush(stdin);
scanf("%c", &yn);
}
return t_trash;
}
int get_lmt()
{
int lmt = 0;
printf("What was last months trash: ");
fflush(stdin);
scanf("%i", &lmt);
return lmt;
}
void print_output(int lmt, int t_trash)
{
float rate = 350.00, charge;
int sum=0, total=0;
if (lmt > t_trash)
{
printf("Total trash tons: %i\n", &t_trash);
printf("Last month's trash: %i\n", &lmt);
printf("Rate: $ %.2f\n", &rate);
}
else
{
printf("What is your tonnage rate: ");
fflush(stdin);
scanf("%.2f\n", &charge);
sum = t_trash - lmt;
total = sum * charge;
rate = rate + total;
printf("Total trash tons: %i\n", &t_trash);
printf("Last month's trash: %i\n", &lmt);
printf("Rate: $ %.2f\n", &rate);
}
}
Now what it should be doing is, The main should be calling the functions on screen as needed.
Now i did all of this with cout cin and it works fine no problems. But when I run this (this is modified to the printf and scanf) it says:
OK UPDATE: Got a ton of it to work. Just one more thing and I should be good. The outcome will not go as expected.
Instead of an output of
last months trash: 100 (asked at the end of the loop)
trash tonnage: 50 (accumulated in the loop)
rate: 350.00 (float variable)
(this is if last month trash was > this month.)
I get just bad numbers all around. It makes no mathematical sense.
Other then that it works fine.
Does the code the the last function look wrong to you guys?

Lots of problems with this code. Lots of them.
1) print_output defintiion takes in a char[100] (char*), print_output declatation takes a char
2) When you pass hauler into print_output, you are passing in hauler[100] (a char, and one pass the end of the array to boot)
3) printf("Name: %s\n", &hauler); hauler is of type char[100] (char*), so &hauler is char**.
there is probably more.

Related

Why scanf is not working in functions using C programming? [duplicate]

This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 1 year ago.
I wrote this C program using 2 functions, but in this first case grade() is not prompting for the input:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Function Type 2\n");
x = motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y = grade();
printf("\nReturned value is %c\n", y);
}
int motivQuote()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n == 1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n == 2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n + 2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade, 1);
return grade;
}
And here in the second case, grade() prompts for the input only in the second call, but the first one is not working:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Functions\n");
x= motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y= grade();
printf("\nSubject2: ");
z= grade();
printf("Returned values are %c and %c\n", y, z);
}
int motivQuote ()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n==1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n==2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n+2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade,1);
return grade;
}
Can anyone tell me what's the reason please?
Use scanf(" %c",&grade,1); with a space before %c. This will solve the problem.

Line breaking issue "C"

I have a noticed a strange bug in my short code. The purpose of this script is to create an array of structures that contain some information about cars
("Struct Car Car1: char brand[50], char model[50], int ccm, int hp, int kw, char[50]")
After running the script everything is fine up until the first instance is filled, but when the variable i has been incremented by 1, the line break disappears from between the lines where I ask the user to provide the "BRAND" and the "MODEL". I am sorry for being a noob this is my first time using structs. Thanks for any kind of help.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#define _CRT_SECURE_NO_WARNINGS
#define MAX 10
int main() {
struct Car {
char brand[50];
char model[50];
int ccm;
int hp;
int kw;
char wheel[50];
};
struct Car Car1;
strcpy(Car1.brand, "Skoda");
strcpy(Car1.model, "Octavia");
Car1.ccm = 1960;
Car1.hp = 170;
Car1.kw = 114;
strcpy(Car1.wheel, "215/75R18");
printf("The car's brand is: %s\n", Car1.brand);
printf("The model is: %s\n", Car1.model);
printf("The volume of the engine is %d ccm\n", Car1.ccm);
printf("It has %d horsepower\n", Car1.hp);
printf("The car has %d kws\n", Car1.kw);
printf("You can put: %s wheels on it\n", Car1.wheel);
struct Car car_arr[MAX];
int i;
for (i = 0; i < MAX; i++) {
printf("Enter details of a car: %d\n", i+1);
printf("\n");
printf("Enter the brand: ");
fgets(car_arr[i].brand, sizeof car_arr[i].brand, stdin); //Brand
car_arr[i].brand[strcspn(car_arr[i].brand, "\n")] = '\0';
printf("Enter the model: ");
fgets(car_arr[i].model, sizeof car_arr[i].model, stdin); //Model
car_arr[i].model[strcspn(car_arr[i].model, "\n")] = '\0';
printf("Enter the parameters of the wheel: ");
fgets(car_arr[i].wheel, sizeof car_arr[i].wheel, stdin); //Wheel
car_arr[i].wheel[strcspn(car_arr[i].wheel, "\n")] = '\0';
printf("Enter the volume of the engine in ccms: ");
scanf_s("%d", &car_arr[i].ccm);
printf("Enter the horsepower: ");
scanf_s("%d", &car_arr[i].hp);
printf("Enter the amount of kilowatts: ");
scanf_s("%d", &car_arr[i].kw);
}
return 0;
}
Tha above comments answered your question, but as a side note:
You can save yourself some repetition by using "typedef" together with "struct".
typedef struct { int x1; long x2; double etc; } my_type;

Unwanted output on second pass using strcpy

I'm reading a book called "C programming Absolute Beginners Guide."
The following program uses some if loops and strcpy to store some character arrays provided by the user. The first pass of strcpy works fine. The second produces garbage. I understand the array needs a \0 to end. According to the book, strcpy does this automatically. What am I missing?
#include <stdio.h>
#include <string.h>
main()
{
int ctr, numMovies, rating, favRating, leastRating;
char movieName[40], favorite[40], least[40];
favRating = 0;
leastRating = 0;
do {
printf("How many movies have you seen this year? ");
scanf(" %d", &numMovies);
if (numMovies < 1)
{
printf("No movies! How can you rank them?\nTry again\n\n");
}
} while (numMovies < 1 );
for (ctr = 1; ctr <= numMovies; ctr++)
{
printf("\nWhat's the name of the movie? ");
printf("(1-word titles only!) ");
scanf(" %s", movieName);
printf("On a scale of 1 to 10, what would ");
printf("you rate it? ");
scanf(" %d", &rating);
if (rating > favRating)
{
strcpy(favorite, movieName);
favRating = rating;
}
printf("%s", movieName);
if (rating < leastRating)
{
strcpy(least, movieName);
leastRating = rating;
}
}
printf("\nYour Favorite Movie was %s.\n", favorite);
printf("\nYour Least-favorite movie was %s.\n", least);
return 0;
}
Because you initialize leastRating to zero you won't have a least favorite unless the rating is negative. Not sure that's what you want.
The best suggestion is from #xing, add a include
#include <limits.h>
and initialize you best and worst like this;
favRating = INT_MIN;
leastRating = INT_MAX;

New to programming. Need help adjusting code to allow for undetermined number of students

Need help adjusting code to allow for undetermined number of students. Tried to modify with help I received last week, but it seems like I am not doing it correctly.
#include <stdio.h>
int main ()
{
/* variable definition: */
char StudentName[100];
float ExamValue, Sum, Avg;
int students,exams;
// Loop through 5 Students
for (students=0; students <5 ; students++)
{
// reset Sum to 0
Sum =0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
// Nested Loop for Exams
for (exams=0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
}
return 0;
}
Not sure how I need to go about changing the code. Any help will be greatly appreciated
Not sure I understand correctly, I understood you want to loop an undertemined amount of students.
I will assume you want to stop if certain keyword is added as a student name, let's say "quit".
Without changing your structure much, it would look like this.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main (){
char StudentName[100];
float ExamValue, Sum, Avg;
int students,exams;
bool in = true;
while (in) {
Sum =0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
if( strcmp(StudentName, "Quit") == 0 || strcmp(StudentName, "quit") == 0){
in = false;
break;
}
for (exams=0; exams < 3; exams++){
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
}
return 0;
}

How to multiplying, multiple inputs from using while loop in c

I have to multiply digits by taking input from the user and when he enter 'n' it will produce the answer.
For example (2*3*2 = 12). But I manage to write the code for taking two inputs but can't find the way to take multiple inputs from user and produce the total answer. Here is the code;
void main (void)
{
float f1,f2;
float total;
int status1,status2;
printf("Enter first number to multiply:'n' to quit.\n ");
status1=scanf("%f",&f1);
printf("Enter another number to be multiply:'n' to quit.\n ");
status2=scanf("%f",&f2);
while (status1==1 && status2==1)
{
total=f1*f2;
status1=scanf("%1.0f",&f1);
status2=scanf("%1.0f",&f2);
}
printf("Multiplition Total = %1.0f",total);
getch();
}
You can use a while loop, as follows.
float prod = 1, f;
printf( "Enter the numbers, n to stop.\n" );
while( scanf( "%f", &f ) )
prod *= f;
printf( "product = %f\n", prod );
Tested:
#include <stdio.h>
int main()
{
int total = 1, factor = 1, success;
do
{
total *= factor;
printf("Enter integer number to multiply or 'n' to quit: ");
success = scanf("%d", &factor);
}
while (success);
printf("Multiplication Total = %d\n", total);
return 0;
}
And a piece of advice as you said you start your adventure with C:
Unless you have some specific reason to do otherwise, use double, not float.
However, in your question you asked for digits (integer) multiplication, so int is sufficient. If you can avoid floating point numbers, avoid them. They're much more complicated then integers and can let you in worse problems if you don't use them with caution.
You can refer to What Every Computer Scientist Should Know About Floating-Point Arithmetic.
This would do what you need and handles, 0, 1 or an unlimited number of inputs:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
float f1;
float total = 0;
printf("Enter number: ");
if (scanf("%f",&total))
{
for (;;)
{
printf("Enter number: ");
if (!scanf("%f", &f1))
{
break;
}
total *= f1;
}
}
printf("Multiplication Total = %f\n",total);
getch();
return 0;
}
It keeps a running total as values are entered but it stops on first invalid input, not just when n is entered.
Untested:
float f, p = 1;
printf ("Enter a number: ");
fflush (stdout);
while (scanf("%f", &f) != EOF)
{
p *= f;
printf ("Enter another number: ");
fflush (stdout);
}
printf ("Product: %f\n", p);

Resources