This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 4 years ago.
Why it is asking for 4 input instead of 3 ?
I have used only 3 scanf in my program.
This is a program about finding smallest and largest number among 3 variables.
Please Help...
#include <stdio.h>
int main()
{
int first, second, third;
printf("Enter 3 integers for compare:");
scanf("%d\n",&first);
scanf("%d\n",&second);
scanf("%d\n",&third);
if((first>second) && (first>third))
printf("First number is the largest\n");
else if((second>first) && (second>third))
printf("Second number is the largest\n");
else if((third>second) && (third>first))
printf("\nThird number is the largest\n");
if((first<second) && (first<third))
printf("First number is smallest\n");
else if((second<first) && (second<third))
printf("Second number is smallest\n");
else if((third<second) && (third<first))
printf("Third number is smallest\n");
return 0;
}
Lets take your last call to scanf:
scanf("%d\n",&third);
The "\n" at the end of the format string means the scanf function will read and discard any white-space after the input, but it can't know when the white-space ends until there is something which is not a white-space character. That means you need to enter some extra input for scanf to be satisfied.
So the simple solution is to just don't have the newlines in your scanf format strings.
Related
This question already has answers here:
Why is my c != 'o' || c != 'x' condition always true? [duplicate]
(5 answers)
Closed 6 years ago.
Does anybody have any idea why this always loops for values different than 1 or 0,and also how can i avoid the endless loop in case of giving a character as input?
#include <stdio.h>
int a;
main()
{
do
{
puts("Give 1 or 0 for input:");
scanf("%d",&a);
} while(a!=0 || a!=1);
printf("\n%d",a);
return 0;
}
The only way for the loop to terminate is if both a!=0 and a!=1 are false. Or in other words: it can only end when a == 0 and a == 1 at the same time. That is of course impossible, so the loop never terminates.
If you want to loop to terminate when the user inputs 1 or 0, then you need a logical and operator there:
do
{
puts("Give 1 or 0 for input:");
scanf("%d",&a);
} while(a!=0 && a!=1);
Aside from that, you really must check the return value of scanf, and purge the input stream in case of failure. If you input a character, then scanf will signify it failed, but leave the character in the input stream. The subsequent iterations will just get stuck on trying to read that character.
One way to do so is with scanf itself and the %*s format specifier.
do
{
puts("Give 1 or 0 for input:");
int read_res = scanf(" %d",&a);
if (read_res != 1)
scanf("%*s");
} while(a != 0 && a != 1);
The asterisk in the format string means scanf will still match any non white-space character and purge them from the stream, but will not attempt to assign them into anything (so no extra parameter is required). I also added a leading white-space to %d in order to disregard any leading white-spaces before the number.
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
C skipping one command of a function? [duplicate]
(2 answers)
Closed 6 years ago.
I've been given the pretty simple task of writing a program that will take two characters and then print the letters inbetween them using a for() loop.
Here's my code:
#include <stdio.h>
int main() {
char a, b;
printf("\nEnter the first character: ");
scanf("%c", &a);
printf("\nEnter the second character: ");
scanf("%c", &b);
for(char i = a; i <= b; i++) {
printf("%c ", i);
}
return 0;
}
When I run it, I am prompted to enter the first character correctly but when I press enter it only runs the next printf() and then terminates.
No errors or warnings or anything on compilation. Another similar question I found that was apparently solved does not work for me either.
Thanks in advance.
You have to consume the \n in stdin left by first scanf.
Fastest fix
scanf(" %c", &b);
The space before %c tells to scanf to ignore all whitespaces before to read the char.
If I read your code correctly, by pressing enter, you would enter the second character, which would most probably (depending on the environment) start with a numeric value of 13, which would be smaller than any letter, so the loop's body is executed only once.
This question already has answers here:
Max string length using scanf -> ANSI C
(5 answers)
Closed 8 years ago.
Sorry I'm sure how to word my question properly.
I'm working on an assignment and I'd like to add a feature to the error checking.
I have a scanf that asks for a word (which is only 5 characters long max).
If the user inputs a string that is 6 characters long like candle, it will only copy over candl.
Here is my take on it. Though I'm sure this isn't the most efficient way to do it.
printf("\n\tEnter word: ");
scanf("%s", input);
if (strlen(input) > MAX_LETTERS){
int i = 0;
while (i < MAX_LETTERS){
word[i] = input[i];
i++;
}
printf("the word is %s", word);
}
Basically checks to see if the input is greater than the max amount of letters allowed. And then if it is, it loops and then only copies over the max amount of letters. Any help would be very much appreciated. Thank you in advance!
scanf("%ns", input);
Where n= number of characters to be read.If in your case it is 5 then have
scanf("%5s", input);
To avoid buffer overflow using scanf() you can specify the number of characters to be read as shown above. Assuming this is what you wanted .
I would always suggest using fgets() while reading strings
fgets(input,sizeof(input),stdin);
You can specify how many characters you want in the second parameter.
PS: fgets() comes with a newline character
This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Store data in array from input [duplicate]
(2 answers)
Closed 8 years ago.
I have the following code:
#include<stdio.h>
#include "commonf.h" //So, this is the way you include from a directory?
void main(){
println("Welcome to Number Guesser v 0.1 ");
println("Think of a number between 0 and 100 (and please, make it an integer!)");
println("Legend: Y=Yes B=Bigger than that S= Smaller than that");
int guessed=0;
float curnum=100.0;
char cursign='?';
while(cursign!='y'){
if(cursign=='?' || cursign=='s'){
curnum=curnum/2;
}
else if(cursign=='b'){
curnum=curnum+curnum/2;
}
else{
printf("You are wrong. Stop it. %c . TEESST",cursign);
}
char askstring[4096];
sprintf(askstring,"%s%f%s","Is your number ",curnum," ? (y/b/s)");
println(askstring);
scanf("%c",&cursign); //Scanf has to expect a new line for some reason.
}
}
(I pasted all of it, since I am a c noob)
If the code looks like this, the loop will execute twice per user input, once with cursign= to whatever the user entered, and once with it equal to \n.
If I change the scanf line to
scanf("%c\n",&cursign);
It asks for the first input twice, then works as a charm. What's the problem, and what should I do?
Change this scanf("%c\n",&cursign); to this scanf(" %c",&cursign);. This will eat up the trailing newline character.
Also as per standard main should return an int (even though this is not the reason for your problem). According to C standards main should be int main(void) or int main(int argc, char* argv[])
When you enter a character like y and hit the ENTER key, a character (which you entered) and a character (which is the enter keystroke - the newline character) gets placed in the input buffer. The first character gets consumed by the scanf but the newline remains in the input buffer so what happens is that the next time you enter something there 3 characters newlinechar + 'y' + newlinechar. So that makes scanf behave funny.
This is a great link from Grijesh - C Printf and Scanf Reference
This question already has answers here:
'printf' followed by 'scanf' requires pressing ENTER key twice to accept input
(2 answers)
Why does scanf ask twice for input when there's a newline at the end of the format string?
(7 answers)
Closed 5 years ago.
I'm beginner in C. Please dont mind if my question is lame. In this program which i have written, when I use 'for' loop first time , I expect only 3 values is stored in an array but it stores 4 values and in next 'for' loop as expected show 3 values.
My Question is why in 1st 'for' loop it takes 4 values instead of 3?
#include<stdio.h>
void main()
{
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d\n",(marks+i));
}
for(i=0;i<3;i++)
{
printf("%d\n",*(marks+i));
}
}
\n in scanf was the problem
#include<stdio.h>
int main()
{
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d",(marks+i));
}
printf("\nEntered values:\n");
for(i=0;i<3;i++)
{
printf("%d\n",*(marks+i));
}
return 0;
}
Reason:
I expect only 3 values is stored in an array but it stores 4 values
and in next 'for' loop as expected show 3 values. My Question is why
in 1st 'for' loop it takes 4 values instead of 3?
First: No, it only stores 3 number but not 4 numbers in array marks[].
Second: interesting to understand loop runs only for three times for i = 0 to i < 3. The for loop runs according to condition. More interesting code is stuck in scanf() as described below:
Your confusion is why you have to enter four numbers, its not because you loop runs 4 times but its because scanf() function returns only when you enter a non-space char (and after some enter press you inputs a number symbol that is non-space char).
To understand this behavior read manual: int scanf(const char *format, ...);:
A sequence of white-space characters (space, tab, newline, etc.; see
isspace(3)). This directive matches any amount of white space,
including none, in the input.
Because in first for loop's, in scanf() you have included \n in format string, so scanf() returns only if press a number enter (or a non-space key).
scanf("%d\n",(marks+i));
^
|
new line char
What happens?
Suppose input to program is:
23 <--- because of %d 23 stored in marks[0] as i = 0
<enter> <--- scanf consumes \n, still in first loop
543 <--- scanf returns, and leave 542 unread,
then in next iteration 543 read by scanf in next iteration
<enter>
193
<enter> <--- scanf consumes \n, still in 3rd loop
<enter> <--- scanf consumes \n, still in 3rd loop
123 <--- remain unread in input stream
remove \n
and i can be created in the if statement as for (int i = 0; i < 3; i++) {}