scanf function not working with characters - c

I was just trying out a simple program in C, inserting into an array.
I used a scanf function to accept characters but it seems the compiler just skipped that and just went to end of the program.
This was the code that I used :-
#include <stdio.h>
void main()
{
int a[50], i, j, m, n, x;
char ch;
printf("Enter the no. elements of the array :- ");
scanf("%d", &m);
printf("Enter the elements below :- ");
for (i = 0; i < m; i++)
{
scanf("%d", &a[i]);
}
printf("The array is :- \n");
for (i = 0; i < m; i++)
{
printf("%d", a[i]);
}
printf("\nDo you want to enter an element ? (Y/N)\n");
scanf("%c", &ch); // The compiler just skips this along with the
while (ch == 'y' || ch == 'Y') // while loop and goes straight to the printf
{ // statement
printf("The index of the element :- ");
scanf("%d", &n);
printf("\nEnter a number :- ");
scanf("%d", &x);
for (i = m; i > n; i--)
{
a[i] = a[i - 1];
}
a[n] = x;
printf("\nInsert more numbers ? (Y/N)");
scanf("%c", &ch);
m = m + 1;
}
printf("\nThe array is :- ");
for (i = 0; i < m; i++)
{
printf("%d", a[i]);
}
}
I used the variable ch in order to allow the user to have a choice, whether or not to insert elements i.e. Y or N.
But the compiler basically skips the third scanf function, the one that accepts the char, along with the while loop.
I just want to know why the scanf function was skipped ?

Back to the previous scanf which is the last array member.
scanf("%d",&a[i])
In the input file if you entered:
32\n
^^
input will wait just before the newline after reading the decimal number.
In the scanf which causes problem:
scanf("%c", &ch);
It will read the newline character as it is available in input that's why it will skip that line after being executed implicitly.
To ignore the whitespace you have only to add space before the specifier %c as stated in comment by #xing and #WeatherVane.
scanf(" %c",&ch);
C99 7.19.6.2
Input white-space characters (as specified by the isspace function)
are skipped, unless the specification includes a [, c, or n
specifier.250)

Related

How do i append proper input as integers to an array in C, as long the user wishes to?

int main(){
char answer;
int numbers[100];
int i = 0;
int size;
int max = -9999;
do{
printf("Please enter an number: ");
scanf("%d", &numbers[i]);
printf("Would you like to keep adding numbers:(Y/N)");
scanf("%c", &answer);
scanf("%c");
i++;
}while(answer == 'Y');
size = sizeof(numbers)/sizeof(numbers[0]);
for(int j = 0; j<size; j++){
if(numbers[j]>= max){
max = numbers[j];
}
}
printf("The max number is: %d", max);
return 0;
}
Hello beginner in C, here in my code i am trying to take an arbitrary amount of (the user enters Y if he/she wishes to enter another number.) input as integers and add them to an array and find the maximum of the input using a for loop, however i am not getting the correct output. What could be the error in my code?
Problems include:
Reading a '\n' when a letter is expected
scanf("%c", &answer); reads the character after the prior input of a number (example:9), which is likely the prior entry's '\n' Enter.
Use a space to consume leading white-space like '\n', space, tab, ...
// scanf("%c", &answer);
scanf(" %c", &answer);
Enable all warnings
Invalid/unnecessary code scanf("%c"); will raise a compiler warning with a well enabled compiler.
Best advice in this answer: enable all compiler warnings to save time.
Start at INT_MIN
The maximum input may be less than -9999.
INT_MIN in <limits.h>
// int max = -9999;
int max = INT_MIN;
Iterate to i
Rather than iterate to 100, only need to iterate to i, the count of values entered.
// for(int j = 0; j<size; j++){
for(int j = 0; j<i; j++){
Check return values
scanf() returns a value indicated the number of successful conversions. Use it to validated input successfully happened.
// scanf("%d", &numbers[i]);
if (scanf("%d", &numbers[i]) != 1) {
; // Report error with TBD code.
}
Do not loop too often
// } while(answer == 'Y');
} while(answer == 'Y' && i < 100);
There is no reason to save an array of values
The maximum could be calculated as data is entered.
int max = INT_MIN;
do {
int num;
printf("Please enter an number: ");
if (scanf("%d", number) != 1) {
break;
}
if (num > max) {
max = num;
}
printf("Would you like to keep adding numbers:(Y/N)");
if (scanf(" %c", &answer) != 1) {
break;
}
} while (answer == 'Y' || answer == 'y');
printf("The max number is: %d", max);
Future Improvements
Handle values outside int range. Research intmax_t.
Detect case of no valid input entered. Research fgets()
Detect non-valid Y/N input. Research fgets()
Recover, rather than quit loop with invalid input.

String not scanned 2nd time when using gets function [duplicate]

This question already has answers here:
Using scanf and fgets in the same program?
(4 answers)
Closed 10 months ago.
When I am using gets function to scan item name in the first loop it runs properly but in the 2nd loop, it skips to Quantity quant without scanning item name.
I also tried using %s previously then it is working fine.
#include <stdio.h>
struct Dmart
{
char item[10];
int quant, price;
};
int main()
{
int i;
struct Dmart cust1[3], cust2[3];
printf("\nFor Customer 1\n");
for (i = 0; i < 3; i++)
{
printf("Item: ");
gets(cust1[i].item);
printf("Quantity: ");
scanf("%d", &cust1[i].quant);
printf("Price: ");
scanf("%d", &cust1[i].price);
printf("\n");
}
printf("\nFor Customer 2\n");
for (i = 0; i < 3; i++)
{
printf("Item: ");
gets(cust2[i].item);
printf("Quantity: ");
scanf("%d", &cust2[i].quant);
printf("Price: ");
scanf("%d", &cust2[i].price);
printf("\n");
}
printf("\nBill of Customer 1\n");
printf("Item\t\tQuantity\tPrice\n");
for (i = 0; i < 3; i++)
{
printf("%s\t\t%d\t\t%d\n", cust1[i].item, cust1[i].quant, cust1[i].price);
}
printf("\nBill of Customer 1\n");
printf("Item\t\tQuantity\tPrice\n");
for (i = 0; i < 3; i++)
{
printf("%s\t\t%d\t\t%d\n", cust2[i].item, cust2[i].quant, cust2[i].price);
}
return 0;
}
[VS Code Terminal Output][1]
The function gets is unsafe and is not supported by the C Standard. So do not use it.
The problem of the code is that after this call of scanf
scanf("%d", &cust2[i].price);
the new line character '\n' that corresponds to the pressed key Enter still is in the input buffer. So the next call of gets reads an empty string encountering at once the new line character.
Instead you could either always use the function fgets and then convert the entered string to an integer for integer data members of the structure or you can use scanf instead of gets like for example
for (i = 0; i < 3; i++)
{
printf("Item: ");
scanf( " %9[^\n]", cust1[i].item);
printf("Quantity: ");
scanf("%d", &cust1[i].quant);
printf("Price: ");
scanf("%d", &cust1[i].price);
printf("\n");
}
Pay attention to the leading space in the format string
scanf( " %9[^\n]", cust1[i].item);
^^^^
It allows to skip white spaces in the input buffer.

Output printed twice instead of once [duplicate]

I tried to execute the following simple code in ubuntu 15.10 But the code behaves odd than expected
#include<stdio.h>
int main(){
int n,i=0;
char val;
char a[20];
printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%c",&val);
int count=0;
for(i=0;i<20;i++){
if(a[i]==val){
printf("\n%c found at location %d",val,i);
count++;
}
}
printf("\nTotal occurance of %c is %d",val,count);
return 0;
}
output:
--------------------------
Enter the value : 12345678
Enter the value to be searched :
Total occurance of is 0
The second scanf to get the value to be searched seems not to be working. The rest of the code executes after the first scanf without getting input second time.
After first scanf(), in every scanf(), in formatting part, put a whitespace
So change this
scanf("%c",&val);
into this
scanf(" %c",&val);
Reason is, scanf() returns when it sees a newline, and when first scanf() runs, you type input and hit enter. scanf() consumes your input but not remaining newline, so, following scanf() consumes this remaining newline.
Putting a whitespace in formatting part makes that remaining newline consumed.
You can use fgets():
#include<stdio.h>
int main() {
int n, i = 0;
char val;
char a[20];
printf("\nEnter the value : ");
fgets(a, 20, stdin);
printf("\nEnter the value to be searched : ");
scanf("%c", &val);
int count = 0;
for (i = 0; i < 20; i++) {
if (a[i] == val) {
printf("\n%c found at location %d", val, i);
count++;
}
}
printf("\nTotal occurance of %c is %d", val, count);
return 0;
}
or clear stdin:
#include<stdio.h>
void clearstdin(void) {
int c;
while ((c = fgetc(stdin)) != EOF && c != '\n');
}
int main() {
int n, i = 0;
char val;
char a[20];
printf("\nEnter the value : ");
scanf("%s",a);
clearstdin();
printf("\nEnter the value to be searched : ");
scanf("%c", &val);
int count = 0;
for (i = 0; i < 20; i++) {
if (a[i] == val) {
printf("\n%c found at location %d", val, i);
count++;
}
}
printf("\nTotal occurance of %c is %d", val, count);
return 0;
}
Also, see C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf
printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%d",&val); // here is different
i don't know why, but code above working...
scanf("%d",&val);
You can use " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.

Program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the factorial of n

The code is supposed to ask the user whether to find the sum of numbers from 1 to x or finding the factorial of x. After taking the user's input for the value of x, the program directly ends without running the if and else if statement. This is my code.
#include <stdio.h>
int sum(int num);
int fact(int num);
int main(void)
{
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x);
printf("Enter f for factorial, s for sum \n");
choice = getchar();
//These lines are ignored by C
if (choice == 'f' || choice == 'F')
{
printf("The factorial of %i is %i \n",x, fact(x));
}
else if (choice == 's' || choice == 'S')
{
printf("The sum from 1 to %i is %i \n",x, sum(x));
}
}
int sum (int num)
{
int sum =0;
for (int i =1; i <=num; i++ )
sum = sum+i;
return sum;
}
int fact (int num)
{
int fact =1;
for (int i =1; i <=num; i++ )
fact = fact*i;
return fact;
}
Can anyone please explain to me what is wrong with my code and how can I fix it? Thank you.
I think buffer problem. So, use
scanf(" %d", &x);
^^^
white-space
instead of
scanf("%d", &x);
and also, use
scanf(" %c", &choice);
instead of
choice = getchar();
The problem in this code is in getchar() function.
In first scanning : scanf("%d", &x); when user press enter key, it remain in the input buffer and the integer val is stored in variable x.
In second scanning: choice = getchar();, it reads the enter key in variable choice.
And you have written only two conditions:
if (choice == 'f' || choice == 'F')
else if (choice == 's' || choice == 'S')
That's why it is directly ending the code; as there is no code written for choice = other than 'f' and 's'
if you write 'else' part like this:
else printf("%d", choice);
It will print: 10 which is the ascii value of Enter / New line feed.
To avoid this, try to make following changes in your code:
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x); //here the integer is scanned in variable 'x'
choice = getchar(); //here the enter key is scanned in variable 'choice' so now input buffer is free
printf("Entr f for factorial, s for sum \n");
scanf("%c", &choice); //here the character entered by use will be stored in variable 'choice' so it is overwritten.

Loop skips a scanf statement after the first time

Here is the code for main():
int main (void)
{
float acres[20];
float bushels[20];
float cost = 0;
float pricePerBushel = 0;
float totalAcres = 0;
char choice;
int counter = 0;
for(counter = 0; counter < 20; counter++)
{
printf("would you like to enter another farm? ");
scanf("%c", &choice);
if (choice == 'n')
{
printf("in break ");
break;
}
printf("enter the number of acres: ");
scanf("%f", &acres[counter]);
printf("enter the number of bushels: ");
scanf("%f", &bushels[counter]);
}
return 0;
}
Every time the program runs through the first scanf works fine but on the second pass through the loop the scanf to enter a character does not run.
Add a space before %c in scanf. This will allow scanf to skip any number of white spaces before reading choice.
scanf(" %c", &choice); is the only change required.
Adding an fflush(stdin); before scanf("%c", &choice); will also work. fflush call will flush the contents of input buffer, before reading the next input via scanf.
In case of scanf(" %c", &choice); even if there is only a single character in the input read buffer, scanf will interpret this character as a valid user input and proceed with execution. Incorrect usage of scanf may result in a series of strange bugs [like infinite loops when used inside while loop].

Resources