Addition not working in c - c

I was trying c code to add but my program doesn't execute, codeblocks unfortunately closes. What is the error?
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,(a+b));
}
I want to put the result of addition directly in printf statement with float inputs but I am not getting it working.
I also tried putting the result in variable a but it didn't work either.
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
}
where am I going wrong?

The problem is in the following statement
printf("%30sAddition Of Numbers\n");
here, the format string supplied to the printf() conatins %30s (or, %s, in general) which is a format specifier (conversion specifier), and you did not supply any argument to it. It invokes undefined behavior.
To quote C11 standard, chapter §7.21.6.1
[...] If there are insufficient arguments for the format, the behavior is
undefined. [...]
You can also check the man page to find out more about the format specifiers.
EDIT:
As discussed in the below comments, if you want some spaces to appear before the output, change
printf("\t\tAddition Of Numbers\n");
That said,
void main() should be int main (void), at least, to conform to the standards.
You should always check the return value of scanf() to ensure the successful scanning.

The "%30sAddition Of Numbers\n" issue in your post has been addressed by two good answers (at the time of this post). But you asked a question in comments that may not have been answered completely:
works with %30s when i use all integer numbers and not float! how do i make it work with floats.
A generic answer to that question:
The format specifier you use in scanf(): "%f",&a could result in undesirable results if scanning in unexpected newlines, spaces or other white space. This can be addressed by modifying the format specifier string to suppress these characters. Here is a suggestion:
char* fmt = "%[^\n]%*c";//This generic format specifier, can be used for both integer
//and floating point inputs when used in conjuction
//with strtod() or strtol() (see below)
scanf(fmt, input);
Explanation of "%[^\n]%*c".
When a user is asked to enter a generic number, it might be a float or an integer. You can accommodate that by creating methods for both, and being specific about what kind of value you would like to process:
float get_float(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter floating point number and hit return:\n");
scanf(fmt, input);
return strtod(input, dummy);
}
long get_int(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}
Called like this:
int main(void)
{
long integer_var = get_int();
float float_var = get_float();
float sum = (float)integer_var + float_var;
return 0;
}

Try adding getch(); function at the bottom before closing curly brackets,
like this
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
getch();//it will hold your output screen so you can see the output
}

In this line
printf("%30sAddition Of Numbers\n");
you did not supply a string argument for the %s format. This causes undefined behaviour.
If you want the output spaced, you could try a small modification
printf("%30s\n", "Addition Of Numbers");
in this case you are supplying a string literal to satisfy the %s format.
Additionally you must always check the return value from scanf to see that it did convert the number of arguments it was supposed to. It's a basic newbie error not to, and the root cause of hundreds of SO questions.

Related

Errors about scanf and printf expected types

My issue is coming from the %c name input, I am getting an error that it is expecting type char * but has type char * [15] for the scanf function. I am also getting an error in the printf where the %c expects int but has type char *. I am still quite new at this so if it could be explained as simply as possible that would be amazing.
#include <stdio.h>
struct Student {
int StudentID;
char Name[15];
float Mark1;
float Mark2;
float Mark3;
} a;
int main() {
float ave;
printf("Please input Student's ID \n");
scanf("%d", &a.StudentID);
printf("Please input Student's name. \n");
scanf(" %c", &a.Name);
printf("Input Mark 1. \n");
scanf("%f", &a.Mark1);
printf("Input Mark 2. \n");
scanf("%f", &a.Mark2);
printf("Input Mark 3. \n");
scanf("%f", &a.Mark3);
ave = (a.Mark1 + a.Mark2 + a.Mark3) / 3;
printf("Student Detail\nStudent ID: %d\nName: %c\nMark 1: %.2f\n Mark 2: %.2f\n Mark 3: %.2f\nAverage: %.2f\n",
a.StudentID, a.Name, a.Mark1, a.Mark2, a.Mark3, ave);
return 0;
}
Your problem is related to the difference between an array of chars and a single char.
The %c format only reads in one character at a time.
If you wish to read a string of characters use %s and it will read until a whitespace. (Please make sure you don't try to read a name more than 14 characters long into your 15 character buffer)
In more depth, your char Name[15] is actually a pointer to a series of chars in memory. You are accidentally trying to change to pointer itself, instead of the chars that it points to. This is why the compiler expects a char * .
Instead if you truly meant to only read one char you could use
scanf(" %c", &a.Name[0]);
to place the character in the first block of the Name array.
If this is too complicated don't worry, it will all come eventually :)
For now I think %s will suffice.
You can use %14s to be extra safe.
Also don't forget to use %s in the final printf as well
In your scanf() call, %c tells scanf() to accept a single character. But your argument is a character array. C is a low-level language; it's not smart enough to realize you wanted a string (char array) as input. You have to tell it by using %s instead of %c.

Using scanf to parse two variables

I'm having a bit of trouble passing multiple variables to scanf:
#include<stdio.h>
int main(void) {
char *name;
float weight;
printf("Please enter your name, then weight separated by a comma: ");
scanf("%s,%f", name, &weight);
printf("%s, your weight is %.2f!\n", name, weight);
return 0;
}
Please enter your name, then weight separated by a comma: Tommy,184
Tommy,184, your weight is 0.00!
What would be the proper way to do this, and why doesn't scanf detect the comma and pull the necessary values in their variables?
There are two mistakes in your code:
Wild pointer
char *name; is not a safe code. *name* is a wild pointer and it points to some arbitrary memory location and may cause a program to crash or behave badly. You should use an array like char name[10]. You can refer to this link.
Comma in scanf
You can check this thread for more details
The comma is not considered a whitespace character so the format specifier "%s" will consume the , and everything else on the line writing beyond the bounds of the array sem causing undefined behaviour
I've just tried to modify your code, you should consider removing the comma, and replace it with a space
printf("Please enter your name, then weight separated by a space: ");
scanf("%s %f", name, &weight); // your code should work properly
I think you should be using a char array for the name variable and if you want to store its adress you would assign it to a pointer, doesn't make sense the way you wrote it
float weight;
char[20] name;
scanf(" %s, %f", &name, &weight);
Can you give this a try?
int main()
{
int num;
char str[50];
scanf("%49[^,],%d", str, &num);
printf("%s %d",str, num);
return 0;
}
EDIT
Explanation:
We can read input up to a specific character/characters using %[^<Your character(s)>]. The number 49 here simply refers to the length of string you'd receive and the last character is a null. Adding specific length is up to you ;) This is just one example of getting input the way you asked.

"static char" vs. "char" in C

To practice variable declaration, placeholders and I/O calls, I did a sample assignment in the book that I am using to study. However, I keep running into a particular problem, in that when I try to declare more than one character variable for the purpose of input, even if the compiler doesn't catch any syntax error, the program when executing will only return one character variable. This is the code in question:
#include <stdio.h>
int main()
{
double penny=0.01;
double nickel=0.05;
double dime=0.1;
double quarter=0.25;
double value_of_pennies;
double value_of_nickels;
double value_of_dimes;
double value_of_quarters;
double TOTAL;
int P;
int N;
int D;
int Q;
char a,b;
//used "static char" instead of "char", as only using the "char" type caused a formatting error where only the latter character entered in its input would appear
printf("Please enter initials> \n");
printf("First initial> \n");
scanf("%s", &a);
printf("Second initial> \n");
scanf("%s", &b);
//"%s" was used as the input placeholder for type "char"
printf("%c.%c., please enter the quantities of each type of the following coins.\n", a, b);
printf("Number of quarters> \n");
scanf("%d", &Q);
printf("Number of dimes> \n");
scanf("%d", &D);
printf("Number of nickels> \n");
scanf("%d", &N);
printf("Number of pennies> \n");
scanf("%d", &P);
printf("Okay, so you have: %d quarters, %d dimes, %d nickels, and %d pennies.\n", Q, D, N, P);
value_of_pennies=penny*P;
value_of_nickels=nickel*N;
value_of_dimes=dime*D;
value_of_quarters=quarter*Q;
TOTAL=value_of_quarters+value_of_dimes+value_of_nickels+value_of_pennies;
printf("The total value of the inserted coins is $%.2lf. Thank you.\n", TOTAL);
//total field width omitted as to not print out any leading spaces
return(0);
}
And this is the transcribed output ("a", "e", and the four "1"s are sample arbitrary input values:
Please enter initials>
First initial>
a
Second initial>
e
.e., please enter the quantities of each type of the following coins.
Number of quarters>
1
Number of dimes>
1
Number of nickels>
1
Number of pennies>
1
Okay, so you have: 1 quarters, 1 dimes, 1 nickels, and 1 pennies.
The total value of the inserted coins is $0.41. Thank you.
I entered the characters "a" and "e" as input values for the char variables "a" and "b", but only "e" had shown up. On the other hand, should I have put a "static" in the "char" variable declaration, both inputted char values will be displayed in the relevant print call.
For future reference, I would like to ask about why such a thing would occur the way that it did, and the value of the "static" word in the declaration.
(As an aside, I am aware that I could have simply made the "value_of_(insert coin here)" variables as constant macros.)
With a definition like
char a,b;
writing a statement like
scanf("%s", &a);
scanf("%s", &b);
invokes undefined behaviour. %s is not a format specifier for a char. Using wrong format specifier can and will lead to UB. You should use %c to scan a char.
To elaboreate,
%s format specifier expects a corresponding argument which is a pointer to char array. It scans multiple characters until it encounters a space (whitespace character, to be pedantic) or newline or EOF.
%c format specifier expects a corresponding argument which is a pointer to char variable. It reads only one char from the input buffer.
So, with %s, if you supply the adress of a char variable, it will try to access beyond the allocated memory region for writing the scanned data, which will invoke UB.
You may want to read some more on printf(), scanf() and format specifiers before moving forward.
You have used the wrong format specifier for char. char uses %c not %s. As far as static goes, I'm a bit confused about your question. You say in a comment that you are using static char, but I do not see any variables declared as static char.

I am getting a couple errors with my C program. Please assist me with whatever I am doing wrong

I know this is probably a really dumb error on my part but I just started learning C. I wanted to make a basic calculator and I keep getting errors about the program expecting a const char * but I have a float. Also it says the last printf command (line 50 i believe) doesn't have the right syntax or correct form. Again I am really new so sorry for the incovinience. Thank you for all the help! My code is below.
#include <stdio.h>
#include <math.h>
int main()
{
char firstnum, secondnum, answer;
char function;
printf("Hello and welcome to my calculator!");
printf("Please input the function you would like to use");
scanf("%c", &function);
printf("Now please input the two variables.");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
if (function == '+')
{
answer = firstnum+secondnum;
}
else if (function == '-')
{
answer = firstnum-secondnum;
}
else if (function == '*')
{
answer = firstnum*secondnum;
}
else if (function == '/')
{
answer = firstnum/secondnum;
}
else
{
printf("Sorry that was an incorrect function. The correct inputs are +, -, *, /.");
}
printf(answer);
return 0;
}
Couple of things:
1)Change line, as you want to use floating point numbers
char firstnum, secondnum, answer;
should be
float firstnum, secondnum, answer;
2)Change line
printf(answer);
to
printf("Answer %f \n", answer);
Declare your variable like so -
float firstnum, secondnum, answer;
and change last printf to -
printf("Answer is: %f", answer);
Your final printf should be
printf("%f", answer);
or the nicer
printf("Answer : %f \n", answer);
This is because the declaration of printf is as follows
int printf ( const char * format, ... );
First parameter expected is the format of the output, the rest are the variables to be inserted.
In addition to this you should fix your datatypes as others have pointed out.
char firstnum, secondnum, answer;
:
scanf("%f", &firstnum);
This is not going to end well at all. You have to match the datatypes in your scanf to the format specifiers.
Those variables should be of type float although, to be honest, there's no real reason not to use doubles nowadays for the extra range and precision. In that case, make sure you use %lf for the format specifiers.
In addition, your final printf is lacking a format specifier totally which means it will attempt to use the answer variable as a specifier. Once you've fixed the data types as per above, this should be changed to:
printf ("%f\n", answer); // %lf for double.
Change your statement to printf("%f",answer);.
Also, you have declared your variables as chars , declare them as floats.
Recommended:
As you seem to be a beginner, I have an advice for you. Try reducing your program execution time and try to make the program efficient. So , instead of so many if---else blocks, you mmay have used switch case.

having trouble with a "\n" and scanf

Here is the code
printf("\n");
printf("Enter a integer vaule:");
scanf("%d" , &num3);
printf("You entered: %015d", num3);
printf("Enter a float value:");
scanf("%f", &deci3);
printf("You entered: %15.2f", deci3);
printf("\n");
the output is
Enter a integer vaule:4.4
You entered: 000000000000004
Enter a float value:You entered: 0.40
The problem is this code is not stopping at
printf("Enter a float value:");
and this scanf
scanf("%f", &deci3);
seems to be getting its value from the previous scanf
The %d conversion stops wherever the integer stops, which is a decimal point. If you want to discard the input there, do so explicitly… getc in a loop, fgets, or such. This also allows you to validate the input. The program should probably complain about 4.4.
The scanf function works this way per the specification:
An input item shall be defined as the longest sequence of input bytes (up to any specified maximum field width, which may be measured in characters or bytes dependent on the conversion specifier) which is an initial subsequence of a matching sequence. [Emphasis added.]
In your example, the following C string represents the contents of stdin when the first scanf call requests input: "4.4\n".
For this initial call, your format string consists of a single specifier, %d, which represents an integer. That means that the function will read as many bytes as possible from stdin which satisfy the definition of an integer. In your example, that's just 4, leaving stdin to contain ".4\n" (if this is confusing for you, you might want to check out what an integer is).
The second call to scanf does not request any additional input from the user because stdin already contains ".4\n" as shown above. Using the format string %f attempts to read a floating-point number from the current value of stdin. The number it reads is .4 (per the specification, scanf disregards whitespace like \n in most cases).
To fully answer your question, the problem is not that you're misusing scanf, but rather that there's a mismatch between what you're inputting and how you're expecting scanf to behave.
If you want to guarantee that people can't mess up the input like that, I would recommend using strtol and strtod in conjunction with fgets instead.
This works, but it dont complains if you type 4.4 for the int
#include <stdio.h>
int main() {
char buffer[256];
int i;
float f;
printf("enter an integer : ");
fgets(buffer,256,stdin);
sscanf(buffer, "%d", &i);
printf("you entered : %d\n", i);
printf("enter a float : ");
fgets(buffer,256,stdin);
sscanf(buffer, "%f", &f);
printf("you entered : %f\n", f) ;
return 0;
}
use a fflush(stdin) function after the fist scanf(), this will flush the input buffer.

Resources