how many times this loop will be executed? - c

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 :)

Related

C Programing : scanf statement is not working in goto [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 6 years ago.
I have this block of code (functions omitted as the logic is part of a homework assignment):
#include <stdio.h>
int main()
{
char c = 'q';
int size;
printf("\nShape (l/s/t):");
scanf("%c",&c);
printf("Length:");
scanf("%d",&size);
while(c!='q')
{
switch(c)
{
case 'l': line(size); break;
case 's': square(size); break;
case 't': triangle(size); break;
}
printf("\nShape (l/s/t):");
scanf("%c",&c);
printf("\nLength:");
scanf("%d",&size);
}
return 0;
}
The first two Scanf's work great, no problem once we get into the while loop, I have a problem where, when you are supposed to be prompted to enter a new shape char, it instead jumps down to the printf of Length and waits to take input from there for a char, then later a decimal on the next iteration of the loop.
Preloop iteration:
Scanf: Shape. Works Great
Scanf: Length. No Problem
Loop 1.
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the shape char.
Loop 2
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the size int now.
Why is it doing this?
scanf("%c") reads the newline character from the ENTER key.
When you type let's say 15, you type a 1, a 5 and then press the ENTER key. So there are now three characters in the input buffer. scanf("%d") reads the 1 and the 5, interpreting them as the number 15, but the newline character is still in the input buffer. The scanf("%c") will immediately read this newline character, and the program will then go on to the next scanf("%d"), and wait for you to enter a number.
The usual advice is to read entire lines of input with fgets, and interpret the content of each line in a separate step. A simpler solution to your immediate problem is to add a getchar() after each scanf("%d").
The basic problem is that scanf() leaves the newline after the number in the buffer, and then reads it with %c on the next pass. Actually, this is a good demonstration of why I don't use scanf(); I use a line reader (fgets(), for example) and sscanf(). It is easier to control.
You can probably rescue it by using " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.
But it will be easier in the long run to give up scanf() and fscanf() and use fgets() or equivalent plus sscanf(). All else apart, error reporting is much easier when you have the whole string to work with, not the driblets left behind by scanf() after it fails.
You should also, always, check that you get a value converted from scanf(). Input fails — routinely and horribly. Don't let it wreck your program because you didn't check.
Try adding a space in the scanf.
scanf(" %d", &var);
// ^
// there
This will cause scanf() to discard all whitespace before matching an integer.
Use the function
void seek_to_next_line( void )
{
int c;
while( (c = fgetc( stdin )) != EOF && c != '\n' );
}
to clear out your input buffer.
The '\n' character is still left on the input stream after the first call to scanf is completed, so the second call to scanf() reads it in. Use getchar().
When you type the shape and ENTER, the shape is consumed by the first scanf, but the ENTER is not! The second scanf expects a number so, the ENTER is skipped because is considered a white space, and the scanf waits for a valid input ( a number) that, again, is terminated by the ENTER. Well, the number is consumed, but the ENTER is not, so the first scanf inside the while uses it and your shape prompt is skipped... this process repeats. You have to add another %c in the scanfs to deal with the ENTER key. I hope this helps!
You can also use
scanf("%c%*c", &c);
to read two characters and ignore the last one (in this case '\n')

What is wrong with my for loop? It turns 2 times when I enter only 1 input in a letter guessing game in C

I know this code is not completed yet, but I cannot go any further because of this issue.
If you execute the code with any compiler you will see it.
After the instructions gets written at console, when you enter a word, loop takes 2 turns. It reduces chance 2 times too when it's supposed to be 1. Why is that?
I am using devc++ and windows.
#include<stdio.h>
#include<stdlib.h>
int main(){
int i,j,totalTrial=6,currentTrial=0;
char myWord [6]={'d','o','c','t','o','r'};
char lineArray [6]={'-','-','-','-','-','-'};
char guess;
printf("Hello,this is a simple word-guessing game. Try to find my secret word. You have 6 chances.");
printf("Lets begin!!\n");
printf("Word:\n------\n");
for(i=0;i<=6;i++)
{
printf("\nGuess a letter: ");
scanf("%c",&guess);
for(j=0;j<7;j++)
{
if(guess==myWord[j])
{
lineArray[j]=guess;
}
}
currentTrial++;
printf("\nResult: %s, %d hakkin kaldi.\n",lineArray,totalTrial-currentTrial);
}
getch();
return 0;
}
This is happening because the scanf() is reading the stray \n (newline character) from the input buffer. [When you are giving input, you must be entering a character followed by ENTER key.]
To resolve this, add a space before % character in scanf() like this:
scanf(" %c", &guess);
This will skip the leading whitespace characters (including newline character) and read the input given by the user.
With regard to the line:
scanf("%c",&guess);
How many characters do you think are turning up when you enter, for example, dENTER? I'll give you a hint, it isn't one :-)
The problem is that your scanf will read each character in turn and process it, including the newline generated when you hit ENTER.
A better solution would be to use a more complete input solution such as this one here.
It will handle many scenarios that a simple method based on scanf or getchar.

Accepting String when format specified is character

I have the below code. I was thinking I should input only one character at a time. But even if I give a string like hello as input in one line, it accepts correctly. Why is this? Is it related to standard input buffer flushing issue?
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
int main()
{
char sourceString [100];
int index=0;
printf("Enter the characters one by one enter * to stop\n");
do
{
scanf("%c",&sourceString[index]);
index++;
} while (sourceString[index-1]!='*');
index=0;
while (sourceString[index]!='*')
{
printf("%c",sourceString[index]);
index++;
}
printf("\n");
return(0);
}
When you enter a string and press ENTER, the whole string goes into the input buffer stdin.
Next, as per the property of %c format specifier, as mentioned in the C11 standard, chapter §7.21.6.2, fscanf()
Matches a sequence of characters of exactly the number specified by the field
width (1 if no field width is present in the directive).
It will match (and scan and store) the first entry (char) in the buffer leaving the rest of the buffer content unchanged.
As you're running the scanf() in a loop, the next call will again go and read from the input buffer ( and continue as long as their is content pending in the stdin buffer).
What's wrong here? It's accepting one character at a time, no matter how many characters there are and putting one character at a time into an array until a condition is met. This is just a (more complicated) way to input a string with an asterisk (*) acting like a null-terminator ('\0').
By the way, you should check the bounds in your first loop. Add something like this or your program will crash with a segfault when the input string gets bigger than 100 characters.
do {
// your code here
} while ((sourceString[index-1]!='*') && (index < 100));
When using scanf you need to terminate the input with a whitespace character(e.g. \n). The scanf will finish reading input when you enter a newline. However since you have a loop it will keep reading input until you enter "*".

Last character in input buffer (C)

I was trying to search for an answer for that but couldn't, hope someone can help.
I have the following snippet of code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c = '\0';
int error = scanf(" %c", &c);
// The user types now the following: A54fG6
while (error != EOF) {
printf("%c", c);
error = scanf(" %c", &c);
}
return 0;
}
Where the first comment is, the input buffer points at A. Then it goes into the while loop, prints the character 'A' and the second scanf advances the input buffer to point at 5. After the last iteration, when the printf printed '6' - the second scanf points at what character?
Or in different words, how can I know when the program finished reading the current input buffer and then do something before the scanf prompts the user for more characters?
First of all, scanf is a function. It points to some code, that runs every time you call it. Not to a character.
The input buffer of scanf is stdin (at least in your case), and it is open while the program is running. Whenever you call scanf, it tries to read from stdin. If it has nothing to read, it asks the user to input something. That's the way it works.
Now, the user may introduce an EOF character, but I don't think this is what you want.

C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 6 years ago.
I have this block of code (functions omitted as the logic is part of a homework assignment):
#include <stdio.h>
int main()
{
char c = 'q';
int size;
printf("\nShape (l/s/t):");
scanf("%c",&c);
printf("Length:");
scanf("%d",&size);
while(c!='q')
{
switch(c)
{
case 'l': line(size); break;
case 's': square(size); break;
case 't': triangle(size); break;
}
printf("\nShape (l/s/t):");
scanf("%c",&c);
printf("\nLength:");
scanf("%d",&size);
}
return 0;
}
The first two Scanf's work great, no problem once we get into the while loop, I have a problem where, when you are supposed to be prompted to enter a new shape char, it instead jumps down to the printf of Length and waits to take input from there for a char, then later a decimal on the next iteration of the loop.
Preloop iteration:
Scanf: Shape. Works Great
Scanf: Length. No Problem
Loop 1.
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the shape char.
Loop 2
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the size int now.
Why is it doing this?
scanf("%c") reads the newline character from the ENTER key.
When you type let's say 15, you type a 1, a 5 and then press the ENTER key. So there are now three characters in the input buffer. scanf("%d") reads the 1 and the 5, interpreting them as the number 15, but the newline character is still in the input buffer. The scanf("%c") will immediately read this newline character, and the program will then go on to the next scanf("%d"), and wait for you to enter a number.
The usual advice is to read entire lines of input with fgets, and interpret the content of each line in a separate step. A simpler solution to your immediate problem is to add a getchar() after each scanf("%d").
The basic problem is that scanf() leaves the newline after the number in the buffer, and then reads it with %c on the next pass. Actually, this is a good demonstration of why I don't use scanf(); I use a line reader (fgets(), for example) and sscanf(). It is easier to control.
You can probably rescue it by using " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.
But it will be easier in the long run to give up scanf() and fscanf() and use fgets() or equivalent plus sscanf(). All else apart, error reporting is much easier when you have the whole string to work with, not the driblets left behind by scanf() after it fails.
You should also, always, check that you get a value converted from scanf(). Input fails — routinely and horribly. Don't let it wreck your program because you didn't check.
Try adding a space in the scanf.
scanf(" %d", &var);
// ^
// there
This will cause scanf() to discard all whitespace before matching an integer.
Use the function
void seek_to_next_line( void )
{
int c;
while( (c = fgetc( stdin )) != EOF && c != '\n' );
}
to clear out your input buffer.
The '\n' character is still left on the input stream after the first call to scanf is completed, so the second call to scanf() reads it in. Use getchar().
When you type the shape and ENTER, the shape is consumed by the first scanf, but the ENTER is not! The second scanf expects a number so, the ENTER is skipped because is considered a white space, and the scanf waits for a valid input ( a number) that, again, is terminated by the ENTER. Well, the number is consumed, but the ENTER is not, so the first scanf inside the while uses it and your shape prompt is skipped... this process repeats. You have to add another %c in the scanfs to deal with the ENTER key. I hope this helps!
You can also use
scanf("%c%*c", &c);
to read two characters and ignore the last one (in this case '\n')

Resources