Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Why the following code is getting terminated after one round if the getchar() in the 5th line is not used?
char s;
while(1){
printf("Enter two integers: ");
scanf("%d%d",&a,&b);
getchar();
c = a + b;
printf("Addition of %d & %d is %d\n",a,b,c);
printf("Add more numbers(yes/no): ");
scanf("%c",&s);
if(s == 'y')
continue;
else
break;
}
And why using string is not working in the following code? I have included the <string.h> file.
char s[10];
while(1){
printf("Enter two integers: ");
scanf("%d%d",&a,&b);
getchar();
c = a + b;
printf("Addition of %d & %d is %d\n",a,b,c);
printf("Add more numbers(yes/no): ");
scanf("%s",s);
if(s == "yes")
continue;
else
break;
}
When you enter the input for the first scanf("%d%d",&a,&b) then you probably ended that with the Enter key.
That Enter key is added as a newline into the input buffer that scanf reads from.
If you don't have the getchar() call then that newline is what the next scanf("%c",&s) will read.
One solution is, as you've noted, to use getchar() to read and throw away the newline. Another solution is to ask scanf to do the same:
scanf(" %c",&s);
// ^
// Note the space here!
The leading space tells scanf to skip and ignore all leading white-space character, of which newline is one such character.
Note that most format specifiers for scanf automatically skip and ignore leading white-space. For example %s will do that, which means your second version with scanf("%s",s) doesn't need the getchar() call.
Also note that this should have been easily deduced by spending five minutes in a debugger to step through the code statement by statement while monitoring variables and their values.
Then for s == "yes". What happens here is that the array s will decay to a pointer to its first element, as will the literal string, and then you compare these pointers to see if they are the same, which they will most likely never be.
It's somewhat simplified equivalent to this:
char yes_literal[4] = "yes";
if (&s[0] == &yes_literal[0]) ...
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 days ago.
Improve this question
/I took input from user as 'a' and 'b' but in 'b' it takes 0 by default ..... whatever i give in 'b' as input it showing 0 as 'b' on applying Operation....
C code ....../
#include <stdio.h>
int main()
{
int a,b;
printf("Enter the I no. : ");
scanf("%d",&a);
printf("Enter the II no. : ");
scanf("%d",&b);
char c;
printf("Enter the Operation : ");
scanf("%s",&c);
switch (c)
{
case '+':
printf("Addtion of %d and %d = %d",a,b,a+b);
break;
case '-':
printf("Subtraction of %d and %d = %d",a,b,a-b);
break;
case '*':
printf("Multiplication of %d and %d = %d",a,b,a*b);
break;
case '/':
printf("Division of %d and %d = %d",a,b,a/b);
break;
}
}
You declared an object of the type char
char c;
So to input a value for the object you need to use conversion specifier %c instead of %s
printf("Enter the Operation : ");
scanf(" %c",&c);
Pay attention to the leading space in the format string. It allows to skip white space characters.
Also before performing division you need to check whether b is not equal to 0.
And it is desirable to include the case label default in the switch statement for an invalid inputted operation.
Also some operations as for example the multiplication can result in overflow. To avoid overflow you should cast operands to the type long long int In this case the calls of printf will look the following way as for example
printf( "Addtion of %d and %d = %lld\n", a, b, ( long long int )a + b );
scanf("%d",&b); appears to be correct code to read a decimal numeral into b. If a non-zero number is entered but b later appears to be zero, a likely explanation is that the mistaken use of scanf("%s",&c); writes a null byte into b.
%s is for reading multiple characters into an array of char. In addition to reading characters from input, it writes a null byte into the array to mark the end of the characters. However, c is a single character, not an array. If you entered a character such as “+” (followed by pressing Enter) then scanf("%s",&c); will write the character into c and then write a null character to the next byte in memory.
If the compiler happened to put b just after c in memory, that will alter the value stored in b.
Do not use scanf("%s",&c); to read a single character. Use " %c". The space character tells scanf to skip white-space (such as the new-line character that will be in the input stream after the user enters a value for b and presses Enter) %c tells scanf to read a single character: scanf(" %c", &c);.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an assignment where i need to find out what scanf("%*[^\n]"); does in a c program. I know that [^\n] means that the input is read until \n and that %* puts the input in the buffer and discards it. I don't understand what usage you can get out of it, because in my understanding it just reads the input till \n and discards it then.
scanf(“%*[^\n]”); usage in a c programm?
It is somewhat common to see yet fgets() is a better approach. Recommend to not use scanf() until you know why you should not use it. Then use it in a limited way.
I don't understand what usage you can get out of it
Example usage: code attempts to read numeric text with scanf("%d", &x); but "abc\n" is in stdin so function returns 0 and data in stdin remains. scanf("%*[^\n]"); clears out (reads and discards) the "abc" in preparation for a new line of input.
int x;
int count;
do {
puts("Enter number");
count = scanf("%d", &x); // count is 0, 1 or EOF
if (count == 0) {
scanf("%*[^\n]"); // Read and discard input up, but not including, a \n
scanf("%*1[\n]"); // Read and discard one \n
}
} while (count == 0);
if (count == EOF) puts("No more input");
else puts("Success");
Variations like scanf(" %*[^\n]"); and scanf("%*[^\n]%*c"); have their own corner problems (1st consume all leading white-space, even multiple lines, 2nd fails to read anything if the next character is '\n').
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:
Program doesn't wait for user input with scanf("%c",&yn);
(5 answers)
Closed 7 years ago.
I managed to make this simple two part program which consists of simple print and scan functions. The first part is an addition operation and the second part asks the user for a letter and then it repeats it to the user. The first part goes well but when it finishes and is supposed to start the second part it shows the whole thing before I can input a letter.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int num1, num2 = 522;/*input a number*/ /*add 522*/
int sum; /*sum of num1 and num2*/
char let; /*Letter to put in*/
printf("Hello, my name is John Doe.\n"); /*Print "Hello my name is*/
printf("Please type a number= "); /*Ask user for num1*/
scanf("%d", &num1); /*Scan for num1*/
sum = num1 + 522; /*Add 522 to num1*/
printf("The sum of %d and %d is %d\n", num1, num2, sum);/*print num1 and sum*/
printf("Please type a letter= \n"); /*Ask user for letter*/
scanf("%c", &let); /*Scan for letter*/
printf("You typed %c\n", let); /*Show the letter input*/
return 0;
}
Change
scanf("%c", &let);
to
scanf(" %c", &let);
There is a newline character after a number is entered so that is picked by %c you need to ignore it. Note the space before %c
A better approach is flushing the input buffer after every scanf()/getchar() call.
while ((ch = getchar()) != '\n' && ch != EOF);
but don't use fflush(stdin) because if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input.
As usual, there are some exceptions, check your compiler's documentation to see if it has a (non-portable) method for flushing input.
you can use getchar() function as well to clean the new line character but first method is recommended.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've made the following but it skips the part where I have to input the character and I don't understand what my mistake is. Any help ?
#include <stdio.h>
main()
{
int num;
float f;
char c;
printf("Input an integer: ");
scanf_s("%d", &num);
printf("Input an floating point number: ");
scanf_s("%f", &f);
printf("Input a character: ");
scanf_s("%c", &c);
printf("\nThe number is: %d\n",num);
printf("\nThe floating point number is: %f\n", f);
printf("\nThe character is: %c\n", c);
return 0;
}
scanf_s("%d", &d);
This reads characters as long as they fit the "%d" format. The first character not fitting that format is the newline you entered. This remains in the input stream.
scanf_s("%f", &f);
This skips leading whitespaces (i.e., your newline), then reads characters as long as they fit the "%f" format. The first character not fitting that format is the newline you entered. This remains in the input stream.
scanf_s("%c", &c);
This reads one character from the input without skipping potential leading whitespace, i.e., your newline.
It also is undefined behaviour: One thing that scanf_s() does differently than standard scanf() is that it demands a "buffer size" numerical parameter for %c and %s, to avoid buffer overflow. Not giving that parameter makes scanf_s() pull an integer from the stack where you didn't put one, resulting in undefined behaviour. If that next memory address happens to be zero, you'll be scratching your head a lot I would bet...
If I'm not wrong your scanf_s("%c", &c); reads the '\n' character from the previous input.
What you can do is add 1 space before %c so:
scanf_s(" %c", &c);
that will fix your issue. Remember you need to do that if reading a character after some previous input.
Tested and works.
Specify the size. Use this line:
scanf_s("%c", &c, 1);
It should work!