Question about input with scanf - c

When I execute the following program it get the user input for account details and then prints it correctly, but it cannot read the opt value (y/n). It automatically calls again. How can I get the program to exit when the user inputs "n"?
char opt;
do
{
//Getting user input
printf("\n Enter the Account Number:\n ");
scanf("%d",&gAccNo_i);
printf("\n Enter the Account Holder's Name:\n ");
scanf("%s",gCustName_c);
printf("\n Enter the Balance Amount:\n ");
scanf("%f",&gBlncAmt_f);
//Printing the input data.
printf("\n Account Number : %d",gAccNo_i);
printf("\n Customer Name : %s",gCustName_c);
printf("\n Balance Amount : %f",gBlncAmt_f);
printf("\n Do u want to wish to continue?(y/n)");
scanf("%c",&opt);
}while(opt!='n');

use opt=getch(); inplace of scanf("%c",&opt);
OR
scanf reads the whitespace that is left in the buffer by previous line. To skip whitespace, add a space to the "%c":
scanf(" %c", &opt);

scanf("%c",&opt);
Will actually read in a space/newline character. Which obviously will not be equal to 'n'.
You may like to take the input as a string and then verify if the first character is a 'n'.
char opts[5];
scanf("%s",opts);
while(opts[0] !='n');

Related

C : when asking for 2 inputs from a user the 2nd question will not prompt an input to be stored in a variable

If I try grade or fullname one at a time I will get the expected result
"Enter your Grade: "
"Your grade is x"
"Enter your full name:"
"Your full name is xxxx xxxx"
If I run below the print out is
Enter your Grade:2
Your grade is 2
Enter your full name: Your full name is
I can't figure out why I am not been prompted for a second input especially as I know it works when tried on its own */
int main()
{
char grade;
printf("Enter your Grade: ");
scanf("%c", &grade);
printf("Your grade is %c \n", grade);
char fullName[20];
printf("Enter your full name: ");
fgets(fullName, 20, stdin); /*2nd argument specify limits of inputs*, 3rd means standard input ie command console */
printf("Your full name is %s \n", fullName);
return 0;
}
scanf("%c"); buffer problem, %c will only eat one character, so or \n will stay in the buffer for the next one to read.
Try this
#include <stdio.h>
#include <stdlib.h>
int main()
{
char grade;
printf("Enter your Grade: ");
scanf("%c", &grade);
getchar(); // here
printf("Your grade is %c \n", grade);
char fullName[20];
printf("Enter your full name: ");
fgets(fullName, 20, stdin); /*2nd argument specify limits of inputs*, 3rd means standard input ie command console */
printf("Your full name is %s \n", fullName);
return 0;
}
use getchar(); to eat the extra character in the buffer.
Don't mix scanf() with fgets() - in this case, the newline present in the buffer, left untouched by scanf() will be fed to fget() and it won't "ask" for any new input.
Better to use fgets() in all the user-inputs.
The problem lies in this line scanf("%c", &grade); Whenever you use scanf() always keep in mind that the enter key will be stored in your buffer. Since enter key was in your buffer, it went right into fullName when fgets(fullName, 20, stdin); is executed. That's way you got your output:
Enter your Grade:2
Your grade is 2
Enter your full name: Your full name is
You can solve the problem by using getchar(); or getch(); right after scanf(); to capture the Enter key and ensures that fullName get the correct input. Another way to solve it is to use fflush(stdin);. They basically do the same thing, but fflush(stdin); clear Enter key from the buffer. Therefore, fflush(stdin); should be used after scanf(); to clear the unwanted Enter key left by scanf();
This is a long one and have a lot to take in, but I hope this information helps :)))

Scanf skips functions

I am working on my assignment and this is the issue that I bumped into. In the assignment, it says that the input value for the middle initals should be this - "L. A.". However, once I run my program it prints some printf functions on the same line, skipping the scanf function. I have went through a lot of topics about that " %c" issue, but I still can not make my program run properly. Some of the variables are from .h file. The actual assignment is bigger, however it is pretty much repetative so I thought if I figure out how to fix this certain issue I will be able to finally finish my assignment.
int main(void){
// Declare variables here:
char ch;
struct Name FullName = { {'\0'} };
struct Address AddressInfo = { 0, '\0', 0, '\0', '\0' };
struct Numbers PhoneInfo = { {'\0'} };
// Display the title
printf("Contact Management System\n");
printf("-------------------------\n");
// Contact Name Input:
printf("Please enter the contact’s first name: ");
scanf("%s", &FullName.firstName);
printf("Do you want to enter a middle initial(s)? (y or n): ");
scanf(" %c", &ch);
if (ch == 'y') {
printf("Please enter the contact’s middle initial(s): ");
scanf(" %s", FullName.middleInitial);
}
printf("Please enter the contact’s last name: ");
scanf(" %s", &FullName.lastName);
// Contact Address Input:
printf("Please enter the contact’s street number: ");
scanf("%d", &AddressInfo.streetNumber);
OUTPUT (I have highlighted input values):
Contact Management System
-------------------------
Please enter the contactÆs first name: *Artem*
Do you want to enter a middle initial(s)? (y or n): *y*
Please enter the contactÆs middle initial(s): *L. A.*
Please enter the contactÆs last name: Please enter the contactÆs street number:
The %s format specifier reads a sequence of characters terminated by whitespace. When you enter L. A., only L. gets read into middleInitial because it stops reading at the space and A. is left in the input buffer. On the next scanf, it immediately reads those buffered characters so it doesn't stop to prompt for anything.
The simplest way to handle this is to leave out the space when inputting, i.e. L.A.. If you want to support whitespace, you'll want to get rid of scanf entirely and read everything a full line at a time using fgets. Note that fgets also reads in the trailing newline, so you'll need to strip that out.

Replacing spaces in string after input?

In the following code when the user enters a space at address the program falls into a infinite loop?
example: street,town, city would crash the program, how can I replace the spaces with a ','? or at least stop this from happening
printf("\nEnter address:\n");
scanf("%s", newNode->address);
printf("\nEnter department:\n");
scanf("%d", &newNode->depart);
while(validDate == 0){
printf("\nEnter Data Of Join(dd/mm/yy):\n");
if (scanf("%d%*[-/. ]%d%*[-/. ]%d", &newNode->day, &newNode->mounth, &newNode->year) != 3){
printf("Wrong format! Please enter a date and exclude the slashes! eg. 15 01 95");
}
else{
// break the loop
validDate = 1;
}
}// date validation end
try
gets()
instead of scanf(). The scanf will stop reading the input when it encounters a space character. And the remaining string data will stay in the input buffer and that may causing the issue.

scanf() gets skipped in for loop

In Windows i used flushall() function to flush all the buffers but this doesnt work in Linux, my scanf() function skips without scanning:
for(i=0;i<n;i++)
{
printf("\nEnter alphabet :");
scanf("%c",&x);
printf("\nEnter frequency :");
scanf("%f",&probability);
/* create a new tree and insert it in
the priority linked list */
p=(treenode*)malloc(sizeof(treenode));
p->left=p->right=NULL;
p->data=x;
p->freq=(float)probability;
head=insert(head,p);
}
Output :
mayur#mayur-laptop:~$ ./a.out
Enter alphabet :a
Enter frequency :2
Enter alphabet :
Enter frequency :a
Enter alphabet :
Enter frequency :2
Enter alphabet :
Enter frequency :a
Enter alphabet :
You should add a space on the beginning of the scanf, and fflush(stdin) before every scanf just to clear the standard input buffer (keyboard by default), like this:
for(i=0;i<n;i++){
printf("\nEnter alphabet :");
fflush(stdin);
scanf(" %c",&x);
printf("\nEnter frequency :");
fflush(stdin);
scanf(" %f",&probability);
/* create a new tree and insert it in
the priority linked list */
p=(treenode*)malloc(sizeof(treenode));
p->left=p->right=NULL;
p->data=x;
p->freq=(float)probability;
head=insert(head,p);
}
EDIT: check if you have char x and float probability
Update: The OP changed the "%d"in the first scanf to "%c" which lets the error, I think, occur later; but franky, I don't feel investing any more time here.--
Original answer: The input is never processed beyond the 'a' because you try reading it with the conversion specification %d for integer numbers which it doesn't satisfy. (In order to read a char you would specify %c.) Scanf puts the offending character back in the input and tries to read the next number which fails again, and so on ad eternum.
It's worth checking scanf's return value which will always be 0 here, indicating that no successful conversion has taken place.

Ambigious nature of scanf taking input before it is asked to enter from user?

#include<stdio.h>
void main(){
int num1,num2;
printf("\n Enter number 1 \t "); // Ask for input one. >>>>>>>> line 1.
scanf("%d ",&num1);
printf("\n Entered number is %d \n",num1);
printf("\n Enter number 2 \t "); // Ask for input Two. >>>>>>>>> line 2.
scanf("%d ",&num2);
printf("\n Entered number is %d \n",num2);
return;
}
I wish to know REASON.Please do provide it.
The code above accepts two inputs,first input is asked(By executing line 1) then user enter one number then terminal should ask to enter second input but instead it is taking other number(before executing line2 ) and then asking to enter second input(i.e after executing line 2).
In the End is is displaying the two input that are taken before executing line two but after executing line 1.
I am confused.I am interested to know reason.
I am using GCC 4.8.2 on ubuntu 14.04 64 bit machine.
Remove spaces between the scanf of access specifier.
scanf("%d ",&num1);
to
scanf("%d",&num1);
Because the scanf get the another value due to that spaces.
And kept in the buffer. After the memory has got it get assigned.
It is for all scanf function.
if I input like
Enter Number1 1
2
Entered number is 1
Enter number2 3
Entered number is 2.
It is better to use int main() and in the end write return 0;
use fflush(stdout); to flush your buffer.
After editing here is the final code
#include<stdio.h>
int main(){
int num1,num2;
printf("\n Enter number 1 \t "); // Ask for input one. >>>>>>>> line 1.
scanf("%d ",&num1);
printf("\n Entered number is %d \n",num1);
printf("\n Enter number 2 \t "); // Ask for input Two. >>>>>>>>> line 2.
fflush(stdout);
scanf("%d ",&num2);
printf("\n Entered number is %d \n",num2);
return 0;
}
Here is the Demo.
You need to put
fflush(stdout);
before the scanf
This will flush your buffer
(also a good idea to check the return value of scanf)
You have given a space in scanf for %d. If you remove that space after %d the program will run
Let's take this apart slowly
#include <stdio.h>
// void main(){
int main(void) {
int num1, num2;
printf("\n Enter number 1 \t ");
scanf("%d ",&num1);
printf("\n Entered number is %d \n",num1);
...
Use a proper function signature for main() - but that is not the main issue.
Code prints "\n Enter number 1 \t "
"%d" directs scanf() to scan for text convertible to an int in 3 steps:
A: Scan for optional leading white-space like '\n', '\t', ' '. Throw them away.
B: Scan for text representing an integer like "+1234567890". If any digits found, save the converted result to the address &num1.
C: Scanning continues in step B until a char that does not belong to the int is found. That char is "un-read" and returned to stdin.
(This is where you get in trouble as suggested by #Chandru) " " directs scanf() to scan for any number (0 or more) white spaces including '\n', '\t', ' ' and others. Then they are thrown away - not saved.
B: Scanning continues!! until a non-white-space is found. That char is "un-read" and returned to stdin.
Lastly scanf() return the value of 1 as that is how many field specifiers were converted. Code sadly did not check this value.
Recall stdin is usually line buffered, which means input is not available to user IO until Enter is hit.
User enters 1 2 3 Enter and scanf() scans the "123" and saves 123 to &num1. Then it scans "\n" as that is a white-space in step 4. and it continues waiting for more white-space.
User enters 4 5 6 Enter and the first scanf() which is not yet done, scans '4', sees it is not a white space and puts '4' back in stdin. scanf() finally returns after 2 lines are entered. At this point "456\n" are waiting in stdio for subsequent scanf().
The second scanf() then perpetuates the issue.
Recommend use fgets() only for all user input, at least until your are very skilled in C.
printf("\n Enter number 1 \t ");
char buf[100];
fgets(buf, sizeof buf, stdin);
if (sscanf(buf, "%d", &num1) != 1) Handle_BadInput();
else printf("\n Entered number is %d \n",num1);

Resources