why loop iterating 6 times but condition is given 5 times [duplicate] - c

This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 3 years ago.
in my code according to for loop Condtion it is clear that it must iterate only 5 times from 0 to 4.
But it is taking 6 input from the user.
Why it is happening.
Please clear my doubt.
#include <stdio.h>
#include <conio.h>
void main() {
int i, num;
clrscr();
printf("Enter 5 elements in the array\n");
for (i = 0; i < 5; i++) {
scanf("%d\n", &num);
}
getch();
}

According to your code i think you are mixing up the inputs you request with the system pause created by the getch() function you call at the end. The getch() initiates a pause which you can easily mix up with your input prompts since during this pause, user input is possible though not considered.
I propose you introduce an instruction in the loop which indicates the line or some information so you can make the distinction.

You have two problems regarding input.
The first is the getch call at the end of the program. But the other problem is the newline in the scanf format string
scanf("%d\n",&num);
When the scanf function sees a space in the format string (newline is considered a space in this context) then it will read and discard all spaces in the input. The problem with a trailing space in a format string is that to know when the spaces in the input ends, there must be some non space input as well.
So (almost) never have a trailing space (space, newline, carriage-return, tab) in a scanf format string.

The reason this code wait 5 times user input is the getch() at the end.
It waits for the input of one character and probably used to prevent the shell window from directly closing after the program finshed.

Related

Can somebody explain why the line of this code containing fgets isn't getting executed? [duplicate]

This question already has answers here:
fgets doesn't work after scanf [duplicate]
(7 answers)
Closed 1 year ago.
#include <stdio.h>
#include <string.h>
int main()
{
int num;
char answer[10];
char affirmation[10]="yes";
do
{
printf("Enter a number : \n");
scanf("%d",&num);
if (num % 97 == 0)
{
printf("No. is divisible by 97!\n");
}
else
{
printf("No. is not divisible by 97!\n");
}
printf("Once More ? [yes/no] \n");
fgets(answer,sizeof(answer),stdin);
}
while(strcmp(affirmation,answer) == 0);
return 0;
}
I expected from this program to check the divisibility of a provided number by 97 and then to ask if I again want it to check for another number if I input "yes". But it isn't prompting for my input .
If anybody can explain the reason behind this problem and suggest some ways to get through, it will be appreciated.The output is given below:
This output is for num = 194.
It is being executed but what it's reading is the newline character in the input stream that wasn't read when you did the scanf.
What your scanf does is to first skip any white space, then read an integer up to but not including the first non-digit character, which is probably the \n generated by the ENTER key.
Then, because fgets reads a line up to the next newline, you get an empty line.
In both the preceding two paragraphs, I'm assuming for simplicity ideal conditions such as ensuring it's a valid integer and that the line is not longer than the size you provided. Obviously, deviating from that could cause unruly behaviour.
It's generally not a good idea to mix the two input types unless you know in great detail what will be in the input stream. It's often better to just use line-based input and then sscanf that into more appropriate variables.
That way, you can be more sure about where your input stream is at any given point.
A quick fix in this particular case is simply to augment your scanf so that it skips to the start of the next line:
scanf("%d",&num);
while (getchar() != '\n') {}
The other problem you'll have after that is the fact that your fgets input will actually be "yes\n" rather than "yes", so that string comparison won't work.
If you're after a fairly robust line input function that takes care of that (and many other things), see here.

Newline character(\n) in scanf [duplicate]

This question already has answers here:
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.
Suppose i write the code below:
#include<stdio.h>
int main()
{
int a,b;
scanf("%d\n",&a);
printf("%d",a);
return 0;
}
The input is taken and the cursor is blinking in the next line without printing the value of a.
But if I remove the \n character, it is printing the value of a automatically in the next line.
Even if I place a \n, before the %d in scanf (scanf("%d\n",&a);), it is not moving the cursor to the next line, and taking the input, instead of being taking input in the next line. So, does scanf automatically takes input in next lines? and does \n cannot be used with the scanf function??
Actually, my problem wants me to input three integers in three line. It is written Input:
Three integers on three lines.
But on trying to use \n in scanf, it is only showing a cursor blinking in the next line after taking the input.
Any whitespace-character (as determined by isspace()) in the format-string for scanf() will cause it to read and discard characters until the next character read would be non-whitespace, or an error occurs.
You didn't enter any other non-whitespace than the number? Well, have fun waiting.

while loop does not execute scanf() [duplicate]

This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 6 years ago.
#include <stdio.h>
int main() {
float change = 0.0;
printf("O hai! ");
while (change <= 0) {
printf("How much change is owed?\n");
scanf("%f\n", &change);
}
return 0;
}
and the result if input is a negative is endless "How much change is owed?"
scanf is actually entered, but due to the \n in format string "%f\n", after having entered a number, scanf waits for the next non-whitespace character to return. Note that a white space in format specifier lets scanf consume a sequence of any white space characters, not only one, and so it "hangs" as long as only white space characters are provided by the stream.
Change scanf("%f\n",&change) into scanf("%f",&change).
When you ask a computer to discard whitespace, how does it know what it's done? Answer: As soon as it reads something that's not whitespace.
You asked it to discard whitespace after reading a number. Thus it's not done until it reads the number and then reads some non-whitespace.
That really doesn't make any sense since there's no reason anyone would enter non-whitespace after entering the number.
Here's a tip though that will save you pain in the future: If what you really want to do is read a line of input then parse it, use a function that reads a line and then some code to parse that input.

how many times this loop will be executed?

I write this code, which takes an integer number (t) as input from the user. A loop will be executed just 't' times. But I find that it runs for (t-1) times. For example, if I give input 3, it runs only 2 times. Can anyone please explain why this is happening?
I tried and used scanf("%s", &str), it works, but then I can't take a string as input that contains spaces.
#include <stdio.h>
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
char str[100];
gets(str);
printf("%s\n", str);
}
return 0;
}
scanf("%d", &t) consumes only the numeral in the input stream and leaves the remaining characters. When you enter a numeral and press enter, there is a newline character after the numeral.
The first gets reads this newline and returns a string that is empty except for the newline. The first iteration of the loop prints this blank line.
Loop is iterating 3 times as it should.But it seems that it is iterating 2 times only because of the reason that the \n character left behind by gets in the buffer is read in second iteration.
For first iteration, when you enter a string and the press Enter, the \n character go to the buffer with the string. gets stop reading when it encounters \0, leaving \n in the buffer. On next iteration this \n (non printable character) is read by gets and then printed to terminal.
NOTE: Never use gets function. It is no longer is the part of standard C. Use fgets instead.
I guess you can also use the scanf function to resolve your problem that the string is not accepting anything after a SPACE . Also, the loop is running (t-1) times because the buffer is not being cleared due to the use of gets() . In order to resolve this, you can use the getch() function to clear the buffer. The following code should work I guess,
#include <stdio.h>
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
char str[100];
scanf("%[^\n]c",&str);
printf("%s\n", str);
getch();
}
return 0;
}
In this code, the getch() will clear the buffer by accepting the useless value. Also as far as scanf() is considered, the ^ inside the scanf tells the function that it needs to take the input till the character after the ^ is encountered which in this case is an escape sequence of NEW LINE . I have tried using some small words as well instead of the newline and it has worked as well. Hope this clears your issue :)

loop executes more than needed [duplicate]

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

Resources