How to write functions that use values from other functions - c

I am a complete beginner at c so please give me advice that is as simple as possible.
I have two questions. How do you use scanf in a function with pointers because my program is not working at all.
Also, how do you write functions that uses values from another function. For example I have to write a function that asks for employee name, hours worked, and hourly rate. And then I have to write another function that uses that information to calculate gross pay and overtime pay.
This is the scanf code I wrote so far:
#include <stdio.h>
#include <stdlib.h>
int employeedata(char *ch, float *x, float *y)
{
printf("Enter your name:\n");
scanf_s("%s", &ch);
printf("Enter your hourly rate:\n");
scanf_s("%f", &x);
printf("Enter number of hours worked:\n");
//variables
scanf_s("%f", &y);
}
int main() {
float rate[5], hours[5];
float overtimerate = 1.5;
char name[5][20];
int loop;
//loop 5 times
for (loop = 0; loop < 5; loop++)
{
//call function
employeedata(name[loop], &rate[loop], &hours[loop]);
//use if to break out of loop after input if -1 is entered
if (strcmp(name, "-1") == 0)
break;
if (rate[loop] == -1)
break;
if (hours[loop] == -1)
break;
}
system("pause");
return 0;
}

You are passing pointer to a pointer in scanf function in line
scanf_s("%s", &ch);
But scanf requires pointers to buckets where you want the read values to be put. Hence the corrected code should be
scanf_s("%s", ch);
Same error in lines
scanf_s("%f", &x);
scanf_s("%f", &y);
which must be
scanf_s("%f", x);
scanf_s("%f", y);
Because x, y & ch themselves are pointers
More:
Here is the prototype for the scanf()
int scanf(const char *format_string, ...);
where "..." (ellipsis) refer to pointers to the buckets.

edit: here is an example for everything you wanted
#include <stdio.h>
#include <stdlib.h>
char *inputString(FILE* fp, size_t size) {
//The size is extended by the input with the value of the provisional
char *str;
int ch;
size_t len = 0;
str = realloc(NULL, sizeof(char)*size);//size is start size
if (!str)return str;
while (EOF != (ch = fgetc(fp)) && ch != '\n') {
str[len++] = ch;
if (len == size) {
str = realloc(str, sizeof(char)*(size += 16));
if (!str)return str;
}
}
str[len++] = '\0';
return realloc(str, sizeof(char)*len);
}
void CalcFunc(double hours, double rate, double* gross, double* otime);
int main(void) {
char *name;
double HoursWorked = 0, RatePerHour = 0, GroosPay =0, OverTime=0;
printf("input name: ");
name = inputString(stdin, 10);
printf("input hours worked: ");
scanf("%lf", &HoursWorked);
printf("input rate per hour: ");
scanf("%lf", &RatePerHour);
CalcFunc(HoursWorked, RatePerHour, &GroosPay, &OverTime);
printf("Name:%s\n", name);
printf("hours worked:%.2f\n", HoursWorked);
printf("rate per hour:%.2f\n", RatePerHour);
printf("over time:%.2f\n", OverTime);
printf("gross pay:%.2f\n", GroosPay);
free(name);
return 0;
}
void CalcFunc(double hours, double rate, double* gross, double* otime) {
//just an example for function
*otime = hours*2;
*gross = hours*rate*0.3;
return;
}

Related

Why does this program crash when I run through the loop a 2nd time?

Try as I might to solve this riddle, I think I'm losing my mind! Can anyone help understand why this program crashes when I run through the loop a 2nd time?
I can run through the interactive loop one time and have the values entered written to a file. However, when I attempt to pass through the a loop a 2nd time, the program chokes.
// C Libraries Used
#include <stdio.h>
#include <math.h>
#include <string.h>
// Constant definitions
const float OTPAYFACTOR = 1.5;
const float REGWORKWKHRS = 40;
FILE *payfile; // report file (for output)
// Variable declerations
char deptname [21];
char firstname [10];
char lastname [10];
char fullname [47];
float hrsworked;
float hrwage;
float reghrsworked;
float othrsworked;
float otwage;
float grosswage;
int count;
char again;
// Function Prototypes
//**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~
// M A I N F U N C T I O N
//**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~**~~
int main (void){
payfile = fopen("c:\\class\\mod6\\ethan-pay.txt","w"); // Open disk file
printf("Mountain Pacific Corporation\nDepartment Salary Program\n\n");
printf("Please enter the name of the department: ");
scanf("%s", deptname);
count = 0; // Initialize this "counting" variable to zero to start
printf("%s", deptname);
printf("\n");
do {
printf("Enter employee #%d: ", count+1);
scanf("%s %s", firstname, lastname);
fscanf(payfile,"%s %s", firstname, lastname);
strcpy(fullname, firstname);
strcat(fullname, " ");
strcat(fullname, lastname);
printf("Enter the hourly wage of %s: ", fullname);
scanf("%f", &hrwage);
fscanf(payfile,"%f", &hrwage);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked);
fscanf(payfile,"%f", &hrsworked);
if (hrsworked <= REGWORKWKHRS){ //
reghrsworked = hrsworked;
othrsworked = 0;
otwage = hrwage * OTPAYFACTOR;
grosswage = hrwage*reghrsworked;
}
else{
reghrsworked = REGWORKWKHRS;
othrsworked = hrsworked - REGWORKWKHRS;
otwage = hrwage * OTPAYFACTOR;
grosswage = (reghrsworked * hrwage) + (othrsworked * otwage);
}
fprintf(payfile,"%-22s%0.1f ($%0.2f) %6.1f ($%0.2f) $%-4.2f\n", fullname, reghrsworked, hrwage, othrsworked, otwage, grosswage);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
count++; // Increment the counting variable
} while (again == 'Y'|| again == 'y' || again != 'N' && again != 'n');
printf("End of processing.\n");
fclose(payfile);
return 0;
}
I don't understand why are you scanning your file that you use for save the result:
scanf("%s %s", firstname, lastname);
fscanf(payfile,"%s %s", firstname, lastname);
// ...
scanf("%f", &hrwage);
fscanf(payfile,"%f", &hrwage);
// ...
scanf("%f", &hrsworked);
fscanf(payfile,"%f", &hrsworked);
What you do erase previous value. Just remove all call to fscanf().
I strongly advice you to change your code practice, global should be avoid, only declare variable when you need them, don't ignore error code from function, provide to scanf() the max size that it can use, etc...
example probably not perfect:
#include <stdio.h>
#include <string.h>
#define OTPAYFACTOR 1.5
#define REGWORKWKHRS 40
int main(void) {
printf("Mountain Pacific Corporation\nDepartment Salary Program\n\n"
"Please enter the name of the department: ");
char deptname[21];
if (scanf("%20s", deptname) != 1) {
return 1;
}
printf("%s\n", deptname);
FILE *payfile = fopen("c:\\class\\mod6\\ethan-pay.txt", "w");
if (!payfile) {
return 1;
}
for (int count = 0;; count++) {
printf("Enter employee #%d: ", count + 1);
char firstname[10];
char lastname[10];
if (scanf("%9s %9s", firstname, lastname) != 2) {
return 1;
}
char fullname[19];
sprintf(fullname, "%s %s", firstname, lastname);
printf("Enter the hourly wage of %s: ", fullname);
float hrwage;
if (scanf("%f", &hrwage) != 1) {
return 1;
}
printf("Enter total number of hours: ");
float hrsworked;
if (scanf("%f", &hrsworked) != 1) {
return 1;
}
if (hrsworked <= REGWORKWKHRS) {
float reghrsworked = hrsworked;
float othrsworked = 0;
float otwage = hrwage * OTPAYFACTOR;
float grosswage = hrwage * reghrsworked;
fprintf(stdout, "%-22s%0.1f ($%0.2f) %6.1f ($%0.2f) $%-4.2f\n", fullname,
reghrsworked, hrwage, othrsworked, otwage, grosswage);
} else {
float reghrsworked = REGWORKWKHRS;
float othrsworked = hrsworked - REGWORKWKHRS;
float otwage = hrwage * OTPAYFACTOR;
float grosswage = (reghrsworked * hrwage) + (othrsworked * otwage);
fprintf(stdout, "%-22s%0.1f ($%0.2f) %6.1f ($%0.2f) $%-4.2f\n", fullname,
reghrsworked, hrwage, othrsworked, otwage, grosswage);
}
printf("\nThank you. Process another employee? ");
char again;
if (scanf(" %c", &again) != 1) {
return 1;
}
if (again != 'Y' && again != 'y') {
break;
}
printf("\n");
}
fclose(payfile);
printf("End of processing.\n");
}
example input:
jurasickpark
sarah connor 5 42
y
bob lennon 9 12
n
output file:
sarah connor 40.0 ($5.00) 2.0 ($7.50) $215.00
bob lennon 12.0 ($9.00) 0.0 ($13.50) $108.00

Program not returning scanned character

So in my class, part of the homework assignment is to have a function that will return a character that's been entered.
I tried to create this sample code, but it's not working as I hoped.
#include <stdio.h>
char readCharacter();
int main(){
char x;
x = readCharacter();
printf("You inputted %c", x);
return 0;
}
char readCharacter(){
char z;
printf("Input character\n");
scanf("% c", &z);
return z;
}
I enter a character, I decided to type w, and the program told me the character was some weird funky font.
The actual code from my homework, or rather a snippet from it, is
#include <stdio.h> // needed by printf, scanf()
#include <ctype.h> // needed by tolower()
#include <stdlib.h> // for exit()
double readNumber(char *prompt) {
double val;
printf("%s", prompt);
scanf("% lf", &val);
//if input is not a number, exit program
if (scanf("%lf", &val) != 1) {
printf("Invalid input.\n");
exit(1);
}
return val;
}
char readYesOrNo(char* prompt) {
char yn;
printf("%s\n", prompt);
scanf("% c", &yn);
return yn;
}
int main() {
double bonus;
char yesNo;
yesNo = readYesOrNo("Did the worker get a bonus ? (y/n) ");
if (yesNo == 'y' || yesNo == 'Y') {
bonus = readNumber("Enter bonus: ");
}
else {
bonus = 0;
}
return 0;
}
In the actual homework code, the readYesOrNo function doesn't even wait for me to input anything, it just displays the prompt asking for a y/n response, then goes on to the next line of code, not waiting for user input and assuming a no response.
I have no clue why this isn't working.
% c is not a valid format specifier. But %c is probably what you meant.
This line:
scanf("% c", &z);
Needs to be this:
scanf("%c", &z);

how to check if user input is a certain character

I am trying to check if the user inputs y or something else.
I have tried creating a string and looping through what the user inputs, but that doesn't work.
char answer[] = "n";
for(int i = 0; i < sizeof(answer)/4; i++) {
if(answer[i] == "y") {
calculatorPrompt();
} else if(answer[i] === "n") {
printf("Okay, bye!");
System(100);
}
}
This is my code (I'm sure it crashes on the if statement):
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%s", answer);
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
calculatorPrompt() function:
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d\n", a) != 1) {
checkNumber();
} else {
printf("Enter your second number: ");
if(scanf("%d\n", b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
}
}
calculate() function:
int calculate(int a, int b) {
return a + b;
}
checkNumber() function:
void checkNumber() {
printf("Really? You didn't enter a number... Now exiting..");
return;
}
I have included <windows.h> <stdio.h> and <stdbool.h>
I'm also confused as to why it crashes.
The return value of the program is -1,073,741,819.
You have multiple issues with scanf() statements in the code :
in calculatorPrompt() funtion of your code, you use :
if(scanf("%d\n", a) != 1) //wrong : sending variable as argument
This is wrong because you need to send address of the variable as the argument not the variable itself as argument.
if(scanf("%d", &a) != 1) //correct : sending address as argument
similarly change while scanning other integers in the code.
here,
char answer = 'n';
scanf("%s", answer);
As you are using the wrong format specifier, this invokes Undefined behavior.
here since answer is a char so, instead use :
scanf(" %c", &answer); //space to avoid white spaces
and as I've already suggested in the comments :
You use i < sizeof(answer)/4 in the for loop
No! it must be i < sizeof(answer), as in a string every element occupies only 1 byte not 4 (you are mistaking it for an int array)
by the way you don't have any strings in your code
I don't recommend the code you have written for calculator, yet wanted to help you find the working code. Try following code that is based on your own code. Hope you'll see the differences and understand the reasons why the program was crashing in your case.
#include <Windows.h>
#include <stdio.h>
#include <stdbool.h>
bool checkNumber(int num)
{
return true;
}
int calculate(int a, int b) {
return a + b;
}
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
scanf_s("%d", &a);
if (checkNumber(a)) {
}
printf("Enter your second number: ");
scanf_s("%d", &b);
if (checkNumber(b)) {
}
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
int main()
{
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf_s("%c", &answer);
if (answer == 'y') {
calculatorPrompt();
}
else if (answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
}
#include <windows.h>
#include <stdio.h>
#include <stdbool.h>
void calculatorPrompt(void);
int main(void){
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%c", &answer);//scanf need address of store place
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!\n");
Sleep(100); //wait for 100 milliseconds
}
return 0;
}
void checkNumber(void);
int calculate(int a, int b);
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d", &a) != 1) {//\n : skip white spaces and wait input not spaces
checkNumber();//call when invalid input
} else {
printf("Enter your second number: ");
if(scanf("%d", &b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d\n", sum);
}
}
}
void checkNumber(void){//output message and clear input.
fprintf(stderr, "invalid input!\n");
scanf("%*[^\n]%*c");//clear upto end of line.
}
int calculate(int a, int b) {
return a + b;
}
When you scan a character , you just need to use %c. If you are planning to continue with string you must use strcmp() for comparison not ==.

Compare strings in C using getchar

I know this has been asked before and I've read through the answers. I also know that my code isn't great as I'm still learning C. I'm trying, without any luck, to compare a user entered char with a char in an if statement. All and any advice is appreciated. Also, I'm aware of buffer issues though just trying to get the comparison to work first.
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(void){
//int n;
//const char *F = "F";
//float temp;
//float converted;
printf("Would you like to enter Fahrenheit or Celcius? Please type F or C: ");
//scanf("%c", &a);
char input = getchar(); //This will get a single Char from the user and keep it as a char
printf("%c\n", input);
//n = strcmp(input, F);
if(input == "C") {
printf("Please enter the temp you would like to convert to Fahrenheit: ");
scanf("%f", &temp);
converted = temp * 9/5 +32;
printf("You entered %2f Celcius and that equals %2f Fahrenheit\n", temp, converted);
}else if(strcmp(input, "f") == 0) || (strcmp(input, "F") == 0){
printf("Please enter the temp you would like to convert to Celcius: ");
scanf("%f", &temp);
}else{
printf("You didn't enter F or C");
}
}
int strcmp ( const char * str1, const char * str2 );
strcmp takes two string variables.
but your input variable is a char. So use if(input == 'C') and if(input == 'F')
You are comparing characters so it should be input=='C'.
By the way don't forget to put dummy getchar() so that the \n doesn't come into the input character.
Also you are using char input in strcmp().
You have not declared temp or converted.
Note: In C you can't compare strings by using ==.
Corrected code
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(void){
//int n;
//const char *F = "F";
float temp;
float converted;
printf("Would you like to enter Fahrenheit or Celcius? Please type F or C: ");
//scanf("%c", &a);
char input[10];// = getchar(); //This will get a single Char from the user and keep it as a char
scanf("%s",input);
printf("%s\n", input);
//n = strcmp(input, F);
if(strcmp(input,"C")==0) {
printf("Please enter the temp you would like to convert to Fahrenheit: ");
scanf("%f", &temp);
converted = temp * 9/5 +32;
printf("You entered %2f Celcius and that equals %2f Fahrenheit\n", temp, converted);
}else if((strcmp(input, "f") == 0) || (strcmp(input, "F") == 0)){
printf("Please enter the temp you would like to convert to Celcius: ");
scanf("%f", &temp);
}else{
printf("You didn't enter F or C");
}
}

Why does this C loop skip the first attempt to input a letter?

This is a program I am making for a class. It is supposed to read a letter from a file, and then in the game the user tries do guess the letter. with every wrong attempt the program tells you if the actual letter comes before or after your guess in the alphabet.
For some reason when I run it, the loop skips the first attempt in the getLetter function and does not let you input the letter. Why is this?
#include <stdio.h>
#include <ctype.h>
#define MaxGuesses 5
void instructions();
int playGuess (char solution);
char getLetter ();
int compareLetters (char guess, char solution);
int main()
{
int numGames;
int i;
char solution;
char guess;
int result;
FILE *inFile;
inFile=fopen("inputLet.txt","r");
instructions();
scanf("%d", &numGames);
for(i=1; i<=numGames; i++)
{
printf ("\nThis is game %d\n", i);
fscanf(inFile, " %c", &solution);
result = playGuess(solution);
if (result == 1)
printf("You've WON!\n");
else
printf("You've LOST :(\n");
}
//close file
fclose(inFile);
return 0;
}
void instructions ()
{
printf ("This game consists of guessing letters.\nThe user will have up to 5 chances of guessing correctly,\nupon every failed attempt,\na hint will be provided regarding alphabetical position.\n\nEnter the number of games you wish to play (max 4): ");
}
char getLetter()
{
char userGuess;
printf("\nPlease enter your guess: ");
scanf("%c", &userGuess);
userGuess = tolower(userGuess);
return userGuess;
}
int compareLetters(char guess, char solution)
{
if (guess == solution)
return 1;
else if (guess < solution)
{
printf("\nThe letter that you are trying to guess comes before %c", guess);
return 0;
}
else if (guess > solution)
{
printf("\nThe letter that you are trying to guess comes after %c", guess);
return 0;
}
}
int playGuess (char solution)
{
int numGuesses = 0;
int winOrLose = 0;
char guess;
while(numGuesses < MaxGuesses && winOrLose == 0)
{
guess = getLetter();
winOrLose = compareLetters(guess, solution);
numGuesses++;
}
return winOrLose;
}
It may be consuming a character left in the input buffer (possibly a newline or other whitespace character). You could try changing the format string from "%c" to " %c" as you've done elsewhere, which will skip all the whitespace characters in the buffer before trying to read a character.

Resources