Compare strings in C using getchar - c

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");
}
}

Related

How to insert a continue statement inside an if statement

My code is below. I am using C language. I want to repeat the action from the start if the user types Y but I am confused how can I make that happen.
I tried to look for a solution but the results doesn't fit for my program.
#include <stdio.h>
int main() {
int A, B;
char Y, N, C;
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2: ");
scanf ("%i", &A);
printf ("= %i", A + B);
printf ("\n\nAdd again? Y or N\n");
scanf ("%c", &C);
if (C == Y) {
//This should contain the code that will repeat the:
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2:
} else if (C == N)
printf ("PROGRAM USE ENDED.");
else
printf ("Error.");
}
You should just wrap your code inside a for loop:
#include <stdio.h>
int main() {
int A, B;
char Y = 'Y', N = 'N', C;
for (;;) { // same as while(1)
printf("Enter value 1: ");
if (scanf("%i", &B) != 1)
break;
printf("\nEnter value 2: ");
if (scanf("%i", &A) != 1)
break;
printf("%i + %i = %i\n", A, B, A + B);
printf("\n\nAdd again? Y or N\n");
// note the initial space to skip the pending newline and other whitespace
if (scanf(" %c", &C) != 1 || C != Y)
break;
}
printf("PROGRAM USE ENDED.\n");
return 0;
}
There are a lot of errors in your program.
Syntax error: please resolve it on your own.
There is no need for Y and N to be declared as character, you can use them directly as they are not storing any value.
NOW, there is no need for continue you can use while loop.
I have resolved your problem. Please take a look
Also, you are using a lot of scanf so there is an input buffer, a simple solution to it is using getchar() which consumes the enter key spaces.
#include <stdio.h>
int main()
{
int A, B;
char C = 'Y';
while (C == 'Y')
{
printf("Enter value 1: ");
scanf("%i", &B);
printf("\nEnter value 2");
scanf("%i", &A);
printf("= %i\n", A + B);
getchar();
printf("\n\nAdd again? Y or N\n");
scanf("%c", &C);
}
if (C == 'N')
{
printf("PROGRAM USE ENDED.");
}
else
{
printf("Error.");
}
}

C language: The Array did not return a correct value

I have an assignment in C language that requires to ask users to enter values to arrays. My idea is createing two different arrays which one contains integer values and the other holds character values. This is my code so far:
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type");
printf(" and Time Input:");
scanf("%c", &instrType[0]);
scanf("%d", &time[0]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
while (continued == 'Y' || continued == 'y')
{
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type ");
printf("Time Input:");
scanf("%c", &instrType[i]);
scanf("%d", &time[i]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
}
return 0;
}
The expected value should be: L1 L2 C3 U1
My Screenshot
The loop just stopped when I tried to enter new values and the condition did not check the value even I entered 'Y' meaning 'yes to continue' please help :(
You are comparing a string with a character that is instead of using scanf("%s",&continued) try using "%c"
The main problem is scanf("%c", &char) because scanf() after had read the input print a \n to pass at the next line, this cause that the next scanf() instead of reading your input, go to read \n, causing the failure in the reading of the input.
To avoid this problem put a space before %c ==> scanf(" %c", &char)
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
do
{
printf("L-lock a resource\n");
printf("U-unlock a resource\n");
printf("C-compute\n");
printf("Please Enter The Instruction Type and Time Input: ");
scanf(" %c%d", &instrType[i], &time[i]);
printf("Continue? (Y/N) ");
scanf(" %c", &continued);
i++;
} while (continued == 'Y' || continued == 'y');
return 0;
}
Other things:
Instead of i = i + 1 you can use i++
Instead of using a while() is better using a do{...}while() for saving some line of code.
You can concatenate more inputs in a single line ==> scanf(" %c%d", &instrType[i], &time[i])

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 write functions that use values from other functions

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;
}

How to loop a whole codeblock in C?

So basically after the calculation the program prompts the user if they want to quit the program and the user inputs a character ('y' or 'n') and if the user puts a number or letter that is not 'y' or 'n' then the program will keep prompting the user until they input one of the characters.
The issue I'm running into is that the program will keep looping and prompting the user even if 'y' or 'n' is inputted. When I try fflush(stdin) it still doesn't work
I want to know how to loop the statement again if the user does not input one of the options and when they do input it properly, how to get the code inside the "do while" loop to repeat. Preferably without having to copy and paste the whole bloc again.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");
scanf("%f", &x);
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
scanf("%f", &t);
}
fflush(stdin);
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
scanf() will not throw away the newline character '\n' in the input buffer unless your format string is set to discard it. In your code, after entering input for your floats and pressing Enter, the newline is still in the buffer. So for the code that prompts Y\N, use this format string to ignore the newline
scanf(" %c",&d);
You can remove the fflush() calls if you do that. In your case, it looks like your loop conditionals are wrong though.
This line
while (d != 'y' || d != 'n')
is wrong.
Think of it like this:
The loop runs if d is NOT 'y' OR d is NOT 'n'
Now imagine you put in 'y'
d is 'y'. The loop runs if d is NOT 'y' OR d is NOT 'n'. Is d != 'y'? No. Is d != 'n'? Yes. Therefore the loop must run.
You need to use &&
while (d != 'y' && d != 'n')
Also, scanf doesn't throw away the newline so add a space for all your scanfs.
scanf("%c", &d); //change to scanf(" %c", &d);
Look in this part-
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
you are using whiletwice, i think you will wish to have a single while condition over here.. also if you are terminating while, then be sure there is a doinvolved.
Here is code which I think is right since you have many problems so i just have changed a lot :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");//delete the repeat scanf
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
}
fflush(stdin);
sum=0;//no initalization
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while ((d != 'y' )&& (d != 'n'))//this logical expression is the right way
{
scanf("%c", &d);
fflush(stdin);
printf("\n****************************************");//I change the pos of print to avoid double printing
printf("\nDo you wish to quit? (y/n): ");
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
ps:for your calculate part of cos I'm not sure about the correctness while runing:)

Resources