i am having trouble with this c language code:
char st[2];
printf("enter first value:");
scanf("%c", &st[0]);
printf("enter second value:");
scanf("%c", &st[1]);
So my computer didn't ask me to enter the second value, I mean to say that it only print the first printf statement then I enter a character and then it only prints the second printf statement and program end without taking the second input.
Please help. What's wrong with this code?
-Thanks in advance.
Well it did. The character(s) produced by the ENTER key is present in the buffer already.
use fflush(stdin); function before the second scanf();. It will flush the ENTER key generated after first scanf();.
Actually, your second scanf() is taking the ENTER as its input and since scanf terminates after getting an ENTER, it is not taking anything else by your side.
I think your problem is the second scanf is receiving the "Enter" key press.
You're getting the implicit newline you entered as the second character, i.e. st[1] is getting the value '\n'. An easy way to fix this is to include the newline in the expected format string: scanf("%c\n", &st[0]);
Change
scanf("%c", &st[0]);
to this
scanf(" %c", &st[0]);
That's a shotty answer (no error checking or anything) but its quick and easy.
Related
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.
#include<stdio.h>
int main()
{
int N,i,j,n,*numArray,count=0;
char **arr,*part1,*part2,*token;
scanf("%d",&N);
arr=(char **)malloc(N*sizeof(char *));
numArray=(int *)malloc(N*sizeof(int));
for(i=0;i<N;i++){
arr[i]=(char *)malloc(50*sizeof(char));
}
for(i=0;i<N;i++){
printf("plz enter %d th :",i);
gets(&arr[i][0]);// why is it not executing
}
for(i=0;i<N;i++){
printf("%s",arr[i]);
}
return 0;
}
I tried executing this code and found that the line gets(&arr[i][0]); does not get executed, i.e. it doesn't wait for user to input. Instead, it prints "plz enter 0 th: plz enter 1 th: plz enter 2 th: and so on" and doesn't wait for user to enter the string.
I am unable to get what exactly is wrong and what exactly is happening? Plese help. Thanks in advance.
This line inputing the number of entries
scanf("%d",&N);
leaves a newline in the input buffer. Then this line
gets(&arr[i][0]);
takes that lone newline as the first entry.
You can get rid of it like this
scanf("%d%*c",&N);
But you should not be using gets in this day and age, it is obsolete. This would have been better for the string entries (instead of the above mod)
scanf("%50s", arr[i]);
as well as checking the return value from all the scanf calls. The code still needs improvemnt though, since as stated scanf will only scan up to the first whitespace.
. it doesn't wait for user to input. Instead, it prints "plz enter 0
th: plz enter 1 th: plz enter 2 th: and so on"
this is due to problem of white space in your loop... instead try consuming them before every time you scan string using scanf(" ");, like this :
for(i=0;i<N;i++){
printf("plz enter %d th :",i);
scanf(" "); //to consume white spaces
gets(arr[i]);// why is it not executing? because of wrong arguments
}
EDIT : as suggested by #user3629249
Never use gets() for two major reasons:
It allows the input to overflow the input buffer
It is removed from the language from C11 onward.
a better alternative would be fgets()
and here's a link to know about it more: here
This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
This is part of a university lab and the TA tells me there is an error but I haven't a clue. When I run it it asks me for the first char but then runs through the program and doesn't ask me at the second scanf.
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
scanf("%c", &sen);
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
scanf("%c", &ben);
printf("The key just accepted is %d", ben);
}
Actually this is C not C++. Save it as file.c.
Try this:
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
sen = getchar();
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
getchar();
ben = getchar();
printf("The key just accepted is %d", ben);
}
Explanation: when you enter the first character and press enter it takes enter's ASCII code as the second.
I suggest not to use scanf. But it works both ways if you put a getchar to "take" the enter.
Adding a space before %c in the second scanf will solve the issue.
This is done because scanf does not consume the \n character after you enter the first character and leaves it in the stdin.As the Enter key(\n) is also a character,it gets consumed by the next scanf call.The space before the %c will discard all blanks like spaces.
When you are scanning a character(%c) using scanf,add a space before %c as it would help reduce confusion and help you. Therefore, in both the scanfs , you can add the space.
When you pressed your key and then hit enter, you typed in two keys. The first was the desired key ,a for example, and the second was the key <enter> typically written as \n. So, your second scanf captures the result \n.
Since printing out the \n character doesn't result in something that is easy to see on the screen, it will appear like your program is just skipping the second scanf and printing out only the fixed parts of the printf without a easily viewable value.
One way to get around this problem is to consume all the key strokes just before the key you want to capture. This is done by accepting more input after the character up until you see a newline character \n. Once you see that character, then you do your next read.
// flush extra input up the to carriage return
char flush = 0;
while (flush != '\n') {
scanf("%c", &flush);
}
// now read my desired input
scanf("%c", &ben);
that's because nobody accepts '\n'. call scanf like this scanf("%c%*c", &sen). %*c means you want to omit one character, which is '\n'.
btw, void main() is allowed. main function is not the real entry point of executable, so it's ok to do that. but it seems not everybody likes it.
In my program I must store input characters in variables and then add them to arrays. But is there a way to use the same variable each time?
char str1,str2;
printf("insert character");
scanf("%c",&str1);
printf("%c",str1);
printf("insert character");
scanf("%c",&str2);
printf("%c",str2);
I would like to do something like this but using one variable. Also can I use scanf more than 1 times? It seems the executable stops before the second character is given.
Yes, you can use scanf() more than once. Your problem is not actually because of scanf();, Its with your input, To give input for first scanf() in your program, what we naturally do is we type(through keyboard) a character and hit ENTER KEY,Under the hood when you hit ENTER KEY a '\n' character is produced which is read by your second scanf() ,that's why your second scanf() is not waiting for input from you as you expected, You need to clear this '\n' manually when you use %c.(when %d %f %s are used '\n' are automatically removed that's why we don't face this problem when using them).
To solve problem you can use "%c" like this " %c" (note space before %c, this skips '\n' characters)
scanf(" %c",&str1);
printf("%c",str1);
//code to add them to array's
scanf(" %c",&str1);//Have Re-Used the same variable str1.
printf("%c",str1);
This question already has an answer here:
Does scanf() take '\n' as input leftover from previous scanf()?
(1 answer)
Closed 9 years ago.
Im trying to make a basic C console application calculator. Yet when i execute it the second scanf command is skipped and the third is run instead. This is a problem as here i need to get operation of the user +, -, *, or /. How do i stop this from happening?
float num1;
char sign;
float num2;
float total;
printf("~~~ Calculator ~~~\n");
printf("Please enter the first number: ");
scanf("%f", &num1);//Get value of num1 from user
printf("\nNow please enter the operation , either +, -, *, or / : ");
scanf("%c", &sign);//Get value of sign from user
printf("\n\nFinaly enter the second number: ");
scanf("%f", &num2);
Edit: Actually after trying various suggestions it seams a space before the %c was the correct way and cleanest way of fixing things. Thanks for the help.
Put a blank character before %c so it will consume the new line character like this:
scanf(" %c", &sign);//Get value of sign from user
After you hit enter, the first scanf consumes the actual number and leaves the \n. The latter is consumed in the next scanf.
scanf("%f\n", &order)
Do that in order to consume the \n you are entering.
As #JonathanLeffler mentioned, it's better approach to use " %c" (Note the space) in the next line in order to consume the newline character.
After the program asking for the first number you enter a number the you hit return. So the the number is stored in the variable num1. But the new line character '\n' still in the buffer you need to clear the buffer before the second scanf is executed Otherwise the signe variable will accept that '\n' as an input because it's a character and it will not prompt for an input.
You should always clear the buffer before asking to input a char
int c;
do {
c = getchar(); // clearing the buffer
} while (c!='\n' && c!=EOF);
printf("\nNow please enter the operation , either +, -, *, or / : ");
scanf("%c", &sign);//Get value of sign from user
Now it shouold work
Actually, this happens because there is still a value in the stdin stream of the program.
An easy solution would be using:
fix: DON'T USE -> fflush(stdin);
Consume the newline char by using scanf("%f\n")...
before the second call to scanf...
Best!