Program not executing completely and skipping statements [duplicate] - c

This question already has answers here:
fgets instructions gets skipped.Why?
(3 answers)
Closed 6 years ago.
I have written a simple program in C which is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int length;
printf("Enter the length of the string:\t");
scanf("%d",&length);
char str1[10];
printf("Enter string:\t");
gets(str1);
printf("%s",str1);
return 0;
}
When I execute it - I get an output as:
Enter the length of the string: 5
Enter string:
Process returned 0 (0x0) execution time : 1.740 s
Press any key to continue.
I don't know why it doesn't ask for the string input and simply quits the program.

When you type '5’ followed by the enter key, you are sending two chars to the program - '5' and newline. So your first scanf gets the '5' and the second gets the newline, which it converts to the number zero.
See How to read a line from the console in C?

When you enter 5 and press enter which is "\n" then "\n" remains in stream and gets assigned to str1. You need to take that "\n" out of the input stream for which many choices are there. You can figure that out. :) Perhaps later I will edit this answer to let you know.
Edit 1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int length;
char c;
printf("Enter the length of the string:\t");
scanf("%d%c",&length, &c);
char str1[10];
printf("Enter string:\t");
gets(str1);
printf("%s",str1);
return 0;
}
This is incorrect way of doing it but your code will at least start working. You can also simply call getc(stdin) which is slightly better. The scanf regex specified in the other answers where it has been marked as duplicate will also work but is ugly and unnecessarily complicated.
I have not tested this and it may not work.

Related

I'm encountering a problem while executing 3 printf() statements [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 6 months ago.
#include <stdio.h>
int main() {
char v1,v2,v3;
printf("enter: ");
scanf("%c",&v1);
printf("enter: ");
scanf("%c",&v2);
printf("enter: ");
scanf("%c",&v3);
}
this is my sample code and I expect an output like:
enter: a
enter: b
enter: c
but I'm getting output like:
enter: a
enter: enter:
2nd and 3rd print statements are getting executed simultaneously.
The problem is that you're reading characters, so if what you enter is actually aEnterbEntercEnter, that is actually SIX characters, and what you read will be the first 3 (the a, the Enter, and the b)
What you can do is use a space in the scanf format to skip whitespace. If you use scanf(" %c", &v1); then any whitespace (such as Enter) will be skipped, which will cause your result to be what you expect. However, if someone enters something like spaceEnter, the program will seem to hang, waiting for non-whitespace to be entered
The problem lies in buffering. Read this question, which was already mentioned in the comments.
TL,DR: Use scanf(" %c", &v); to read chars, since it ignores all whitespace from the buffer, as well as the trailing newline.
Hello what I would recommend is using a library that allows you to use a function called get_char.
I wrote a program using this function that does what you wanted yours to do.
#include <stdio.h>
#include <string.h>
#include <cs50.h>
int main(void)
{
char v1 = get_char("enter: ");
char v2 = get_char("enter: ");
char v3 = get_char("enter: ");
}
So the program stores 3 char values as they are entered one after another, without all executing at once. I don't know if this is the type of answer that you are looking for or if it will help you, but I figured I would put this out there. If its not really what your looking for let me know!
This is what the terminal looks like btw.:
$ make help
$ ./help
enter: a
enter: b
enter: c

How does error-checking works in this question?

/*source: stralloc.c*/
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *A;
int max=0;
//need to add error-checking
printf("enter max string length: ");
scanf("%d",&max);
while ((getchar())!='\n');
A=(char *)malloc(max+1); //room for \0
printf("enter string: ");
fgets(A,max,stdin);
printf("Third char is: %c\n",*(A+2));
//printf("Third char is: %c\n",A[2]));
exit(0);
}
I got this code from my class, but there is one part I don't understand. What does while ((getchar())!='\n'); do in this function?
Can anyone explain it to me?
while ((getchar())!='\n');
Program execution continues at this line until it receives new line character(i.e Enter)'\n'. 'getchar()' method waits until it receives some input from keyboard. Once input is received it is compared with ('\n') if it is not a '\n' it calls getchar() again.
flowchart
while ((getchar())!='\n');
The above line means, it will keep reading from the input stream until newline character '\n' is encountered.

While loop printing and scanf [duplicate]

This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 6 years ago.
this program with this value :
ABCDEF
is ok at the frist
but again when you enter a value with space,like :
ABC DEF
the program works wrong!!!!
while loop ignores scanf the second time
What am I doing wrong?!
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(){
bool checkSrc = false;
bool checkDst = false;
while (!checkSrc && !checkDst)
{
char ins[10];
printf("White Player : ");
scanf("%s",&ins);
}
}
%s - String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).
I recommend you using fgets() instead of scanf() since the latter has no buffer overflow protection.
#define namesize 15
char *ins = malloc (namesize);
fgets(ins, namesize, stdin);

C language:scanning of input string is skipped inside for loop [duplicate]

This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 8 years ago.
Whenever the code is executed, the contents inside the for loop are not executing for the first time, i.e., when i=0. But the loop executes after i=0, i.e., for i=1,2,3,..n-1. Can anyone explain what's wrong here?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char string[30][100];
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++){
gets(string[i]);
printf("%s\n",string[i]);
}
getch();
return (EXIT_SUCCESS);
}
you can either try leaving a space after the scanf so the system pauses there instead of automatic increment the reason for this is after you press enter for the value of n , theres no system pause and one of the i values from loop is automatically considered as entered by the system :
scanf("%d ", &n);
or make the loop be from 0 till equal to n which will still skip a number but at the same time add 1 just to keep the loop equal to the input "n" u give
for(i=0;i<=n;i++)
bear in mind that the first option is much wiser to use since you might need to use the "n" in some other part of the program as well.
for(i=0;i<n;i++)
{
fflush(stdin); //Clears the buffer.insert this here.
gets(string[i]);
printf("%s\n",string[i]);
}
After execution of scanf("%d",&n); you are leaving '\n'(when you press Enter key at the end) character in buffer.Which should be cleared before execution of any other input operation.fflush(stdin) will clear the keyboard buffer. There are many other ways to do it.But using fflush(stdin) is easy for beginners.

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