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 6 years ago.
Improve this question
I have a code written in c:
int num1,num2;
while(1)
{
scanf("%d",&num1);
scanf("%d",&num2);
}
I want to break out of this loop when input is not given when the program runs.
You asked, and that is much, much more than I normally see.
Try the following:
int num1, num2;
while (1) {
if (scanf(" %d %d", &num1, &num2) != 2) {
/* End of input (Ctrl+D)? */
if (feof(stdin))
break;
/* No, just invalid input. */
fprintf(stderr, "That was not two integer numbers. I'm out.\n");
break;
}
printf("You supplied %d and %d.\n", num1, num2);
}
You see, the scanf family of functions returns the number of successful conversions. Above, if scanf() does not read and convert two integers, we check if it failed because it encountered end of input (if it did, then feof(stdin) is true). Otherwise, it must have failed because the input was something else. We cannot retry, because the unparseable input is still unread -- the next try would just fail the same way. (There are ways to consume the bad input, but I'd just read the input line-by-line, and try and parse (or reject) each line instead.)
I see so much code that never checks the return value of any of the scanf family of functions, and so many questions on the behaviour caused by it (incorrect input causing endless loops, maybe out of memory situations, buffer overruns), that it sometimes feels futile to even read a question related to any scanf() function. But, you asked. (And, the other you, reading this question and answer but not being the OP, are interested in the matter.) That is good. That means, perhaps someone actually cares about writing robust programs that don't get into a hissy panic whenever the input diverges just a bit from the expected. I want robust programs.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an assignment where i need to find out what scanf("%*[^\n]"); does in a c program. I know that [^\n] means that the input is read until \n and that %* puts the input in the buffer and discards it. I don't understand what usage you can get out of it, because in my understanding it just reads the input till \n and discards it then.
scanf(“%*[^\n]”); usage in a c programm?
It is somewhat common to see yet fgets() is a better approach. Recommend to not use scanf() until you know why you should not use it. Then use it in a limited way.
I don't understand what usage you can get out of it
Example usage: code attempts to read numeric text with scanf("%d", &x); but "abc\n" is in stdin so function returns 0 and data in stdin remains. scanf("%*[^\n]"); clears out (reads and discards) the "abc" in preparation for a new line of input.
int x;
int count;
do {
puts("Enter number");
count = scanf("%d", &x); // count is 0, 1 or EOF
if (count == 0) {
scanf("%*[^\n]"); // Read and discard input up, but not including, a \n
scanf("%*1[\n]"); // Read and discard one \n
}
} while (count == 0);
if (count == EOF) puts("No more input");
else puts("Success");
Variations like scanf(" %*[^\n]"); and scanf("%*[^\n]%*c"); have their own corner problems (1st consume all leading white-space, even multiple lines, 2nd fails to read anything if the next character is '\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.
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!
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 8 years ago.
Improve this question
I am trying to prompt a user to enter two non negative values. If the user inputs a negative value the program asks user to re-enter a non negative value. Here is what my C program looks like thus far, please explain if I am misusing operators.
int main()
{
int a,b;
do {
printf("enter two positive integers\n");
scanf("%d""%d", &a, &b);
} while (a<0 || b<0);
printf("thank you");
return 0;
}
Even though some people think
scanf("%d""%d", &a, &b);
is wrong, and should be changed to:
scanf("%d %d", &a, &b);
It is not. It is regular in C. Adjacent string literals are concatenated automatically.
Nevertheless there is no need to use that much " symbols for no particular use.
You must check the return value of scanf(). Unless it returns 2, you cannot rely on a and b both having valid values.
Checking the return value of scanf() can be done directly, for instance you could have:
if(scanf("%d %d", &a, &b) == 2)
{
if(a >=0 && b >= 0)
break;
}
But, that said, it's often better to do this in two steps:
Read a full line of input from the user, using fgets().
Try to scan out the two numbers from that single line, using sscanf(). Note the additional s at the start of the function name, here!
The above makes it more robust, since scanf() has rather complicated handling of whitespace.
It looks fine except you have an extra \" in your scanf. It should be:
scanf("%d %d", &a, &b);
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 8 years ago.
Improve this question
/* Program Print Prime Numbers */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int *primes=NULL;
int trial=0;
bool found=false;
size_t total=0;
size_t count=0;
printf("\nHow many primes would you like?\n");
scanf("%d",&total);
total=(total<4?4:total);
printf("%d",total);
primes= (int*)malloc(total*sizeof(int));
if(primes==NULL)
{
printf("\nNot enough memory\n");
return 1;
}
*primes=2;
*(primes+1)=3;
*(primes+2)=5;
count=3;
trial=5;
while(count<total);
{
trial+=2;
for(size_t i=0;i<count;i++)
if(!(found=(trial % *(primes+i))))
if(found)
*(primes+count++)=trial;
}
for(size_t i=0;i<total;i++)
{
if(!(i%5))
printf("\n");
printf("%d",*(primes+i));
}
printf("\n");
return 0;
}
This a C program from a book that i use to learn C Programming.
This program doesn't work.
When it should input the "total" variable, the program continue to input values.
How many primes would you like?
4
5
10...like this
... but when i input “total” it doesn't start.Where is the mistake?
Without commenting about the other problems, the reason that it doesn't start is that it goes into an infinite loop because you say:
while(count<total);
Remove the trailing ;.
scanf() is blocking call reading input from stdin until EOL is read. This means you have to start the program, type the desired number of primes and press enter, to end the input.
EDIT:
Some clarifications:
stdin is standart input. By default it's keyboard input.
EOL means end of line. It's a character marking end of line.
Blocking call means, that the program stops until the the call is finished. Functions for input are generally speaking blocking. Very simply put, the program is removed from processor, no instructions are executed, until the call is finished, unblocking the program.
The problem isn't with scanf() or enter as some suggested - this could be easily seen by fflushing the output after the first printf.
I found the source for your code, and you forgot a little important break which does all the difference:
while(count<total)
{
trial+=2;
for(size_t i=0;i<count;i++)
if(!(found=(trial % *(primes+i))))
break; // <-------------------- HERE.
if(found)
*(primes+count++)=trial;
}
Also, as suggested, there should be no trailing semicolon after the while clause-opening.
Just press "Enter" button to force your "scanf" to return its read value