Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have started learning C and I want to make an addition program.
I have written the following code:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
int a,b,c;
scanf("Give a,b",&a,&b);
c=a + b;
printf("A+b=",c);
printf("\n\n\n");
return 0;
}
It is supposed to take 2 numbers from the users and show their sum.
However the only output I get after the user writes 2 numbers is A+b=
Any ideas?
You failed to include a format specifier for your integer variable c. Without this printf doesn't know what arguments to expect following the format string, what their types are, or how they are to be printed. Change:
printf("A+b=",c);
to:
printf("A+b=%d",c);
Note that a good compiler with warnings enabled (e.g. gcc -Wall ...) would have pointed out this simple mistake for you at compile-time.
Also your scanf usage is wrong - change:
scanf("Give a,b",&a,&b);
to:
printf("Give a,b");
scanf("%d %d",&a,&b);
You're missing the %d conversion specifier in the printf() call:
printf("a+b=%d\n", c);
Without that, printf() doesn't know it's getting a second argument and won't do anything with it.
Of course, that c could just be a + b, there's no need to store the sum in a separate variable just to print it.
Also, you need specifiers in scanf(), it should be:
scanf("%d %d", &a, &b);
The first argument to scanf() is not a prompt that's printed, it's describing the expected input.
Last, you should check the return value of scanf() to make sure it's 2 before relying on a and b having valid values. I/O can fail, you need to make sure your program does the right thing if that happens.
scanf is a function used to take in input from the user. You are expecting it to print something, ain't you? You need printf instead:
printf("Give a,b\n"); //\n at the end is good
Now, use scanf to scan in the input:
scanf("%d %d",&a,&b);
You are also missing the %d format specifier in the last printf as other answers have mentioned.
scanf() is an input C function (scan with formatting) that uses format specifiers (%datatype ex: %d or %i = int, which is what you want, or %c = char) to store a data entry in given format, provided by the stdin (keyboard buffer) up to and including a null (\0) termination char(in the case of a string);
The Ampersand (&) in C is used to designate/return the memory address (where variable is stored), as opposed to the value of the variable.
scanf("Give a,b",&a,&b);
c=a + b;
printf("A+b=",c);
The issue with above first line of code is that you forgot to include the format specifiers (%d or %i would both work in this case, as I assume you are adding integers and not floats/etc).
Thus the solution to your first problem is an easy one:
scanf("%d %d",&a,&b);
Also, it seems that you are attempting to combine an input and output in one line.
Printf, like scanf, can use format specifiers, or it can contain only a string of characters, and prints to the stdout (console).
What you want to do is include a prompt asking the user for input before storing said input. You add the \n "newline" character at the end to ensure to provide spacing between other outputs and inputs, among many other reasons when you get into char arrays[], aka strings. But for now, this should do the trick:
printf("Give a,b\n");
scanf("%d %d",&a,&b);
Hope this helps both with the current assignment and with general/C programming concepts!
Related
Just like printf(), I was trying to use optional specifiers in scanf() format string. I tried to use the width and precision specifier. Now in printf() it simply reserves the columns and print according to these specifiers but what happens with scanf()? Like what is meaning of %3d and %3.3f here? Is this even relevant in case of scanf()? I have a little idea that width in this case represents the number of characters that are to be read for some particular format but not sure. Below code explains this further:
#include<stdio.h>
int main()
{
int a;
float b;
printf("Enter Numbers:\n");
scanf("%3d %3.3f",&a,&b);
printf("Entered Numbers are\n");
printf("%d %f",a,b);
return 0;
}
Since you specified in the comments that what you really want to know is 'what if i forcefully try to do it' ... Here are the results (with Clang)
warning: invalid conversion specifier '.'
and
warning: data argument not used by format string
The program compiles , however, since these are just warnings.
Upon executing the binary, and entering the variables asked for:
The "%d" for a gets stored properly.
Regardless of what value is entered, the " %3.3f " for b always stores 0.000000
In short, the it does what almost any other code that compiles with warnings does - not behave as intended. This is neither undefined, nor unspecified behaviour, but it is wrong.
Suggestion : Refrain from asking questions that are of the nature ' what happens if I try to compile this '. Just try and see for yourself !
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm really struggling with isdigit();
I need to test for simple numbers, the relevant part of my code looks like this:
printf("Enter a number\n");
scanf("%f", &a);
if (isdigit(a))
printf("That's a number");
doesn't matter what I input, it won't acknowledge it as a number. I saw somewhere an answer to a similar problem, where they said you can only pass the ASCII code to isdigit if you want accurate evaluation (so only 48-57 will work). Instead '2' for example will be interpreted as the 'start of text' I couldn't find any answer on how to get around that though. I don't remember having that problem in cpp.
Any suggestions?
The isdigit function expects a character code and returns true if the character is one of '0' - '9'.
What you are doing by using the %f format specifier is reading in some text which gets interpreted as a floating point and is then parsed to result in the actual value encoded in the system floating point format (probably IEEE754).
You don't want scanf to interpret the values for you. You want to read the text directly. So declare a char array big enough to read your input and use the %s format specifier. This will give you a string. Then inspect each character in the string with isdigit.
isdigit() checks if a single character is a digit or not. You're passing something that's not a single character.
It would be helpful to have a complete code snippet so we could e.g. know the data type of a. Since you've passed %f to scanf(), presumably it's a float?
If so, the scanf() will return 1 if it is able to parse a float out of whatever input it is given. You can use the return value to determine if the input was valid and not have to even use isdigit().
If you want to use isdigit() for some reason, then you should read the input as a string (scanf("%s", ...something that is a char *...)) and then iterate over each character, passing it to isdigit()
The definition for isdigit() is
int isdigit( int ch );
Checks if the given character is one of the 10 decimal digits: 0123456789.
The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.
Returns:
Non-zero value if the character is a numeric character, zero otherwise.
Since you are passing the input to a float variable it will not work.
#include <stdio.h>
#include <ctype.h>
int main() {
unsigned char c;
printf(">");
scanf(" %c", &c);
if(isdigit(c)){
printf("Is a digit\n");
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm a Java programmer trying to learn C for a class and man, I can't wrap my head around this. There's no reason why this shouldn't work and yet it doesn't. I'm trying to write a simple calculator app, and no matter how I write it, the first number I input (variable a) ends up being 0, but the 2nd one is fine. With 5 + 6 as input, the output is 6. What am I missing?
#include <stdio.h>
int main()
{
long int a, b, c;
char op;
c = 0;
printf("Enter the expression: ");
scanf("%ld %s %ld", &a, &op, &b);
switch(op){
case('+'): c = a+b; break;
case('-'): c = a-b; break;
case('*'): c = a*b; break;
case('/'): c = a/b; break;
default: break;
}
printf("\n%ld", c);
return 0;
}
The scanf function returns the value of the macro EOF if an input failure occurs
before the first conversion (if any) has completed. Otherwise, the function returns the
number of input items assigned, which can be fewer than provided for, or even zero, in
the event of an early matching failure.
So always check if scanf is successful and if the number of items are correctly assigned.
And it is good to know about the conversion specifiers (what follows after % character) and the length modifiers and their meanings in C.
Check out C Committee Draft (N1570) sections 7.21.6.2 The fscanf function and 7.21.6.4 The scanf function and you will get a good idea of how to use scanf.
I am not sure if you are giving 5<space>+<space>6 or 5+6(without spaces) as input. If you are doing the first, then try doing the second one, i.e, number1+number2 without spaces between the characters.
And remove the spaces in the scanf("%ld %s %ld") too.
Hope this helps.
This question already exists:
scanf to read multiple data types from one input
Closed 8 years ago.
I am trying to read in an equation in the form of mx+b=y where m, b, and y are integers and x is a character. How do I read in both integers and characters and check that the user inputs the data in that exact form. That is, I somehow need to check that the user inputs a '+' sign an '=' sign and uses the correct variable. eg) I want it to accept mx+b=y but not mX+b=y or another example: accept mx+b=y but not mx-b=y. And I also need it to ignore any additional input after the equation.
I've tried using something like:
scanf(" %d %c %c %d %c %d", &m, &x, &sign, &b, &equal_sign, &y);
Using this format it reads in the first number correctly but skips putting the next character into the variable x and instead puts it in sign.
Sorry for the lengthy wording but I'd appreciate any help and just let me know if I need to clarify anything. Thanks.
I would read the entire line using getline(3) or perhaps fgets(3) then manually parse the buffer containing the line, using strtol(3) with a given end pointer, or sscanf(3) (explicitly testing the returned count, and perhaps using the %n format specifier).
You might want to parse an expression into an AST, e.g. using some recursive descent parsing technique. See also the infix-calc example of GNU bison
If you are sure that your input is exactly of the form a x + b = c (which is unnatural for 3x+-5=8, since you want to type just 3x-5=8) you could use a mix of strtol. See also strncmp(3) and strtok(3)
PS. Follow all the links I am giving you here. They are all relevant!
Get the equation in string format(buffer) and parse this buffer using the sscanf function. By using scanf function there may be a problem of flush kind of things
when you got input prompt , you should try to input one value than tab than another value than tab..and so on .until you entered all values.
scanf(" %d %c %c %d %c %d", &m, &x, &sign, &b, &equal_sign, &y);
first value you entered will be assign to m,
after press tab
second value will be assign to x
press tab..
do this until you entered all values..
In the below code when I entered 'a' value as 3.4(i.e. float) it is giving me answer garbage value without even allowing me to enter the 'b' value and when I given 'a' value as 3 and 'b' value as 2.3(i.e. float) it is accepted and giving me answer 5 not a garbage.
My question is why type checking was not happening on second parameter ;why only on first parameter?
more clearly if I give 3,3.5 code is working but why cant i give input as 3.5,3 ?
int sum(int k,int l)
{
int s= k+l;
return s;
}
void main()
{
int a,b,k;
printf("enter the numbers");
scanf("%d",&a);
scanf("%d",&b);
k= sum(a,b);
printf("the value of sum is %d", k);
}
PS: I saw this question on quora. I was not happy with the answers provided there. I thought SO is the best place to ask this question.
Type checking is not the issue in your program. Type checking happens at compilation time; the behavior you're seeing occurs at run time. There is an issue with compile-time type checking for printf, scanf, and similar functions, which I discuss below, but that doesn't apply to your program, which does pass arguments of the correct type to both scanf and printf. Nevertheless, I'll discuss that issue below (because I wrote about it before I read your question closely enough).
You call scanf twice to (attempt to) read two int values. The input is 3.4, which would be valid input for a float or double. So what does scanf do with this?
scanf with a "%d" format reads input formatted like an optionally signed integer literal, stopping when it sees anything that doesn't match that format. So the first scanf reads just the 3 and stops at the .. It doesn't consider that the . might be a decimal point because you didn't ask it to read a floating-point value. The . isn't an error, it's just the end of the input that scanf("%d", ...) is looking for.
The second scanf attempts to read another int value, but now the first character in the input stream is the ., which cannot be part of a valid integer literal, so it fails. (Examining the return value of scanf would tell you this; it returns the number of items successfully scanned.)
You should always check the results returned by input functions and write code to handle failure (even if you handle it just by aborting the program with an error message).
A safer way to read numeric input is to read an entire line at a time using fgets(), and then parse the line in memory using sscanf. That can have problems too, but it won't leave invalid input characters waiting to be read by later calls (unless you have a very long input line). Read the documentation of fgets and sscanf for more information -- and again, always check the results they return so you can detect input errors.
Both printf and scanf are variadic functions, meaning that they can accept a variable number and types of arguments.
The declaration of printf, for example, is:
int printf(const char *format, ...);
This means that the first argument in a call to printf is checked against the parameter type, but the zero or more following arguments are not checked at compile time. This gives you tremendous flexibility, but at the cost of compile=time checking. It's almost entirely up to you to ensure that all the following arguments are of the types specified by the format string. If you pass an argument of the wrong type (e.g., printf("%d\n", 1.5)), you won't necessarily get an error message; instead, the behavior is undefined.
scanf is similar, but with different semantics for the format string (most arguments are pointers rather than values to be printed).
Some compilers (gcc in particular) will do additional checking for you if the format string is a string literal, but this is not required and other compilers might not do this.
Incidentally, the code you posted is missing the required
#include <stdio.h>
and void main() should be int main(void). If you're using a book or tutorial that suggests using void main(), it was probably written by someone who doesn't know the C language very well. Find a better one.
When scanf encounters a double for variable 'a' as you noted 3.4. It reads 3 as the integer and stops at the decimal. the .4 will then be read as a double on the next call. It works when the second input is a float because it drops the decimal and is not called again thus ignoring the remaining decimals.
As noted in the comments, read about scanf and make some changes to the code.
I think you should add "getchar()" after scanf method,when you press enter,the '/n' will give
next parameter.
it's just my point.
void main()
{
int a,b,k;
printf("enter the numbers");
scanf("%d",&a);
getchar();/* the /n is last in stdin*/
scanf("%d",&b);
k= sum(a,b);
printf("the value of sum is %d", k);
}