Confusion with scanf() or if() - c

I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it.
After entering the data in the first scanf() always gives the option else(): "Error".
I was looking for possible options for the problem. I found a lot of things like that, but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?
#include <stdio.h>
#include <string.h>
int main()
{
float celsius, fahrenheit;
char tempConvering[10];
printf("Enter what to convert to what (F to C; C to F): ");
scanf(" %s", &tempConvering[10]);
if(strcmp(tempConvering, "F to C") == 0)
{
printf("\nEnter temperature in Fahrenheit: ");
scanf(" %f", &fahrenheit);
celsius = fahrenheit * 1.8 + 32;
printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
}
else if(strcmp(tempConvering, "C to F") == 0)
{
printf("\nEnter temperature in Celsius: ");
scanf(" %f", &celsius);
celsius = (fahrenheit - 32) / 1.8;
printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
}
else
{
puts("\nError!");
}
}

I believe there's an error with how you're using scanf, specifically, at this point:
scanf(" %s", &tempConvering[10]);
^
|
+---- here
The second argument to scanf should be the address of the place to store the result. Here, you're saying "place the string that's read in in the memory just after the buffer that I've set up," which isn't probably want you wanted to do. Instead, write this:
scanf(" %s", tempConvering);
This says "place the string inside the buffer named tempConverting." If you're just getting started with C and haven't learned much about pointers and arrays, a good rule of thumb is that if you're reading a string with `scanf, you should just give the name of the array variable where you want to store the string rather than using an ampersand.
Hope this helps!

#include <stdio.h>
#include <string.h>
int main()
{
float celsius, fahrenheit;
char tempConvering[20];
printf("what do you want to convert? ");
scanf("%s", tempConvering);
if(strcmp(tempConvering, "Fahrenheits") == 0)
{
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit - 32) / 1.8;
printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
}
else if(strcmp(tempConvering, "Celsius") == 0)
{
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = celsius * 9 / 5 + 32;
printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
}
else
{
puts("\nError!");
}
}
This was the answer. I have to thank you for the tips, I will try to remember all the details about the scanf(). However, the problem disappeared only when I changed the desired answer not to "F to C" but to "Fahrenheits". Well, respectively, I changed the question. The program instantly earned. Nevertheless, attempts to do something with the scanf() are unsuccessful, to the extent that the same thing happens with the fgets().
In any case, somehow the problem is solved, thank you all!

Don't put extra space while you execute the scanf() function.
This might be an issue sometimes!
This should work fine:
scanf("%s", tempConvering);
By the way, while you take a string as an input, there is no need to use & before the string name.
Someone has already described the details above.

Related

Converting temperatures from Celsius to Fahrenheit

I wrote a program that converts temperatures from Celsius to Fahrenheit. When I enter c, the code works as expected, but when I enter f, it gives me a random number:
#include <stdio.h>
int main (void){
float f,c;
printf("x=Ende c=Umrechnung c->f f=Umrechnung f->c:");
if(scanf("c",&c)==c){
printf("Grad Celisius =");
scanf("%f",&c);
f=(c*1.8)+32;
printf("%.2f Grad Celisius sind %.2f Grad Fahreiheit\n",c,f);
}
else if(scanf("f",&f)==f){
printf("Grad fahrenheit =");
scanf("%f",&f);
c=(f-32)/1.8;
printf("%.2f Grad Fahrenheit sind %.2f Grad Fahrenheit",f,c);
}
return 0;
}
How can I fix my problem?
You didn't use the scanf() command properly. I modified your code a little bit and this works for me:
#include <stdio.h>
int main (void){
float f,c;
char ch;
printf("x=Ende c=Umrechnung c->f f=Umrechnung f->c:");
scanf(" %c", &ch);
if(ch=='c'){
printf("Grad Celsius =");
scanf("%f",&c);
f=(c*1.8)+32;
printf("%.2f Grad Celsius sind %.2f Grad Fahrenheit\n",c,f);
}
else if(ch=='f'){
printf("Grad Fahrenheit =");
scanf("%f",&f);
c=(f-32)/1.8;
printf("%.2f Grad Fahrenheit sind %.2f Grad Celsius",f,c);
}
return 0;
}
Basically, you have read a character (ch) only once and compare it afterwards to the options that your program provides. Please note the space character in " %c" in the scanf() line. It might be needed so that the code works properly, as described here.
I guess that you also want to put a loop around your code, so that it makes sense to ask the user to enter an x in order to end the program. Currently the program terminates if you don't enter c or f. The program also terminates after one calculation has been done.
By the way, I also changed one Celsius to Fahrenheit in your last printf(). I think you confused the words there. I also changed Celisius to Celsius.

Why does it keep on giving me this error in c

float fahrenheit;
float celsius;
float formulaf = (fahrenheit - 32.0) * 5/9;
char str[20];
float formulac = celsius * 9/5 + 32.0;
printf("Choose either fahrenheit or celsius; ");
scanf("%*s", &str);
if (strcmp(str, "fahrenheit") ==0)
{
printf("Enter the temperature in fahrenheit: ");
scanf("%f", &fahrenheit);
printf("%.2f fahrenheit is %.2f celsius", fahrenheit, formulaf);
}
else
{
printf("Enter the temperature in celsius: ");
scanf("%f", &celsius);
printf("%.2f celsius is %.2f fahrenheit", celsius, formulac);
}
I'm coding this in xcode, I have created the headers and everything, this is the main part where I am stuck, it gives an error in the following code and it gives breakpoints in some other lines, please help me solve this
scanf("%*s", &s); -------> data argument not used by format string
what does this mean?
If you read e.g. this scanf reference you will see that the "*" modifier in the format string means the scanned string will not be used.
Also, when scanning for strings, you should not use the address-of operator, as strings already are pointers.
%*s instructs scanf to scan and discard the sting scanned. The compiler is complaining because the second argument of that scanf(&s) is not used.
You probably wanted to use %s or %19s(tells scanf to scan a maximum of 19 characters + 1 for the NUL-terminator) which prevent buffer overflows.
Also change the second argument of scanf to s. This is done because %s expects a char* while &s is of type char(*)[20]. s gets converted into &s[0], a char*, exactly what %s expects.
So the scanf
scanf("%*s", &str);
should be
scanf("%s", str);
for the reasons explained above.
BTW, Your code exhibits Undefined Behavior because when you use
float formulaf = (fahrenheit - 32.0) * 5/9;
and
float formulac = celsius * 9/5 + 32.0;
farenheit and celsius are uninitialized. Move it after they get initialized,i.e, move it after
scanf("%f", &fahrenheit);
and
scanf("%f", &celsius);
respectively.

C - printf inside "if" statement doesn't show

I'm trying to make this printf inside the if statement show, but it doesn't. Here is the code, I've highlighted the printf section.
char conv;
float cel;
printf("Enter what you'd like converted: \n\t1.Celcius to Fahrenheit\n\t2.Inch to CM\n\t3.CM to Inch\n");
scanf_s("%c", &conv);
// This one
if (conv == '1')
printf("Please enter amount of Celcius: \n");
scanf_s("%f", &cel);
float fahr;
fahr = 33.8 * cel;
printf("Conversion of %f Celsius is %f Fahrenheit", cel, fahr);
getch();
return 0;
What is the reason for this?
In looking at the line: scanf_s("%c", &conv);
I see the function scanf_s(),
which in not in any C library that I'm familiar with.
However, the function scanf(), which is in the C libraries,
has the following prototype and usage:
int scanf(const char *format, ...)
where the return value is the number of items in the variable parameter list '...'
that were actually filled from the input.
I.E. your code should, after the call to scanf_s() check the return code
those value should be 1 in your example.
Then you have this code:
if (conv == '1')
printf("Please enter amount of Celcius: \n");
scanf_s("%f", &cel);
supposedly with the idea that all those following lines would be
enclosed in the 'if' block.
however, only the first line following the 'if' is actually part of the
'if' block.
To correct this problem, write the code using braces to delineate
the 'if' block, like this:
if (conv == '1')
{
printf("Please enter amount of Celcius: \n");
scanf_s("%f", &cel);
float fahr;
fahr = 33.8 * cel; // BTW: this is not the correct conversion formula
printf("Conversion of %f Celsius is %f Fahrenheit", cel, fahr);
}

Math equation won't be read. Why is this?

Sorry for not adding the whole code. Dumb mistake on my part.
#include <stdio.h>
int main(int argc, char ** argv) {
float celcius, fahrenheit, kelvin, interval;
int c, f, k;
char temp;
printf("which temperature is being input? (C,F,K) ");
scanf("%s", &temp);
if(temp == 'c') {
printf("enter a starting temperature");
scanf("%f", &celcius);
fahrenheit=celcius*9/5+32;
kelvin=celcius+273.2;
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
}
else if(temp == 'f') {
printf("Please enter a starting temperature");
scanf("%f", &fahrenheit);
celcius=fahrenheit-32*5/9;
kelvin=fahrenheit-32*5/9+273.2;
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
}
else if(temp == 'k') {
printf("enter a starting temperature");
scanf("%f", &kelvin);
fahrenheit=kelvin-273*1.8+32;
celcius=kelvin-273.2;
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
}
}
So it asks for what temperature is being input and the starting temperature but why isn't it calculating the math equation?
It is calculating the math equations
fahrenheit=celcius*9/5+32;
kelvin=celcius+273.15;
but you are not printing it.
Try this
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
And do not forget to change scanf("%s", &temp); to
scanf(" %c", &temp);
temp = tolower(temp); // include <ctype.h> header
or better to place
int c;
while ((c = getchar()) != `\n` && c != EOF);
after scanf(" %c", &temp);. This will eat up all the character other than the first character of the input.
As per OP's comment;
How can I do it so that the Temperature name appears on top of the temperature?
printf("celcius \tfahrenheit \tkelvin);
printf("%5f\t%5f\t%5f", celcius, fahrenheit, kelvin);
Looks like it is calculating, but you're printing the wrong variables. Try replacing c, f, and k with celsius, fahrenheit, and kelvin in the print statement.
You have to be consistent in your variable names, you can't mix them up like you are.
Because you are calculating it like so:
fahrenheit=celcius*9/5+32;
kelvin=celcius+273.15;
However this line is not printing it out, since you have the wrong variables:
printf("%f, %f, %f", c, f, k);
Change that to the proper variable name and type like so:
printf("%f, %f, %f", celcius, fahrenheit, kelvin);
You did not show how you defined your variable temp, but it is extremely dangerous to read a string in this way. If temp is a character, then pointing to the address of it and treating it as a string is asking for trouble. For sure you will have a '\0' written to the location right after temp, and if the user inputs more than a single character the damage they could do is even larger.
You can read a single character with a getc call:
temp = getc(stdin);
I would recommend that you make sure it is lower case - since you are comparing with c:
temp = lower(getc(stdin));
Then obviously, when you print out a variable, you must print out the one you computed. You compute celcius, etc - but your print statement is
printf("%f, %f, %f", c, f, k);
c, f, and k may be valid variables - but they are not the ones you computed in the lines before. Replace the print statement with
printf("Celsius: %.1f; Fahrenheit: %.1f; Kelvin: %.1f\n", celcius, fahrenheit, kelvin);
Or, if you want the name above the number:
printf("\tC\tF\tK\n\t%6.1f\t%6.1f\t%6.1f\n", celcius, fahrenheit, kelvin);
Note the use of \t - the tab character - to get things to align (approximately) and the format specifier %4.1f to say "number in a field width of 6, with one significant digit after the decimal".
One more note - it's Celsius, not celcius. But that is the least of your problems.

Why is printf working but scanf isn't?

Alright so I have to create a weather program and when I try running the code, I get no errors but it will just print the "enter a starting temperature" and the "enter an ending temperature". However it won't let me input the data for it. Is there anything I need to change? I know I haven't completed the code but I just wanted to test out the inputs before continuing with the rest of the code. Thanks for the help!
#include <stdio.h>
int main(int argc, char **argv)
{
float celcius, fahrenheit, kelvin, ending, interval;
int c, f, k, temp;
printf("which temperature is being input? (C,F,K) ");
scanf("%d", &temp);
if (temp == c)
{
printf("enter a starting temperature");
scanf("%f", &celcius);
printf("enter an ending temperature");
scanf("%f", &ending);
fahrenheit = celcius * 9 / 5 + 32;
kelvin = celcius + 273.15;
}
if (temp == f)
{
printf("enter a starting temperature");
scanf("%f", &fahrenheit);
celcius = fahrenheit - 32 * 5 / 9;
kelvin = fahrenheit - 32 * 5 / 9 + 273.15;
printf("enter an ending temperature");
scanf("%f", &ending);
if (temp == k)
{
}
printf("enter a starting temperature");
scanf("%f", &kelvin);
fahrenheit = kelvin - 273 * 1.8 + 32;
celcius = kelvin - 273.15;
printf("enter an ending temperature");
scanf("%f", &ending);
}
}
This:
if (temp == c)
is comparing the newly-read value in temp to the undefined value in the uninitialized variable c. This is undefined behavior.
You probably meant
if (temp == 'c')
to compare against a character, but then you also need:
char temp;
if (scanf("%c", &temp) == 1)
{
if (temp == 'c')
{
/* more code here */
}
}
Note that checking the return value of scanf() helps make the program more robust, and avoids further uses of uninitialized values (if scanf() fails to read something, you shouldn't read the destination variable since it won't have been written to).
if (temp == c)
You are comparing temp with an uninitialized value of c
same for
if (temp == f)
then every thing will be working fine , to make it more user friendly , put a '\n' in printf's
like this,
printf("enter a starting temperature \n");
Here:
printf("which temperature is being input? (C,F,K) ");
scanf("%d", &temp);
you ask for a character to be input, but then you try to scan for an int. This will throw off all the rest of your scanf() calls.
Your variable temp is declared as an integer. Indeed, scanf() wants to read an integer (%d), but gets a char.
Therefore, you read temp as a char.
Furthermore you may use
9.0/5.0
instead of
9/5
Furthermore, using the switch statement would increase the readability.

Resources