Scanf Function And Integers - c

I know that when getting char one should be aware of it consuming white spaces too.
This is not the case in
scanf("%d", &num)
But in the case of:
case 2:
printf("Please enter first number: \n");
scanf("%d", &num1);
printf("Please enter second number: \n");
scanf("%d", &num2);
break;
If the user enters:
444 5
the first scanf gets 444 and the second gets 5, even those they did not press enter.
it there a way to get only one int and end the scanf if the user presses backspace?

for this you could
read the whole line using fgets for instance
sscanf the line for only 1 integer
like this:
char buffer[80];
fgets(buffer, 80, stdout);
if (sscanf(buffer,"%d",&value) == 1)
{
// scan succeeded
}

You can use
while ((getchar()) != '\n');
to wait until the "enter" key is pressed
case 2:
printf("Please enter first number: \n");
scanf("%d", &num1);
while ((getchar()) != '\n');
printf("Please enter second number: \n");
scanf("%d", &num2);
break;

Related

Why does the space is required before %c in order to make the code work?

THAT'S REALLY INTERESTING
wrong code
#include <stdio.h>
int main( )
{
char another;
int num;
do
{
printf("Enter a number: ");
scanf("%d", &num);
printf("\nWant to enter another number y/n ");
scanf("%c", &another);
}while(another == 'y');
return 0;
}
OUTPUT:
Enter a number: 23
Want to enter another number y/n
C:\Users\Shivam Singh\Documents\Let's C\From Book\Ch3>
To differentiate between the wrong and right code please look at the %c. The only difference in both the codes is a space which is just before %c in the right code.
right code
#include <stdio.h>
int main( )
{
char another;
int num;
do
{
printf("Enter a number: ");
scanf("%d", &num);
printf("\nWant to enter another number y/n ");
scanf(" %c", &another);
}while(another == 'y');
return 0;
}
OUTPUT:
Enter a number: 23
Want to enter another number y/n y
Enter a number: 54
Want to enter another number y/n n
The space is required for scanf() to consume the pending newline left in stdin by the previous scanf() that read a number and stopped consuming characters right after the last digit. Without this space, scanf() will store the next byte into another, most likely the newline that was typed by the user to submit the number.
Note that you should also test the return values of scanf()to detect invalid input or premature end of file.

Next printf comes before my scanf takes input

I am creating a calculator file in C with a while loop and a switch statement. The first time through the while loop, everything works fine, but when it goes through the second time, the my printf gets called before I have the opportunity to enter the data into the preceding scanf.
I have tried using '\n' before the text in the printf and I have also tried using fflush(stdout) before and after the scanf call.
Current output:
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: A
Enter both numbers in required sequence: 50 50
// the output of the calculator does <>= 100 // Equal to 100.
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: Enter both numbers in required sequence:
What I want:
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: A
Enter both numbers in required sequence: 50 50
// the output of the calculator does <>= 100 // Equal to 100.
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: // then I can enter a new choice for the switch //
The code I've tried:
while(input != 'q'){
printf("Welcome to the Calculator\nOperation choices:\tAddition(A)\n\t\t\tSubtraction(S)\n\t\t\tMultiplication(M)\n\t\t\tDivision(D)\nEnter choice: ");
fflush(stdout);
scanf("%c", &input);
fflush(stdout);
printf("\nEnter both numbers in required sequence: ");
scanf("%f %f", &num1, &num2);
switch(input){
case 'A':
result = num1 + num2;
break;
case 'S':
result = num1 - num2;
break;
case 'M':
result = num1 * num2;
break;
case 'D':
result = num1 / num2;
break;
default:
printf("Please choose a valid operation.");
break;
}
if(result > 100){
printf("Greater than 100.\n");
}
else if(result < 100) {
printf("Less than 100.\n");
}
else{
printf("Equal to 100.\n");
}
}
printf("Quit the menu.\n");
return(0);
}
The sequence of events in you program is correct, what happens is that scanf() reads a lingering '\n' new line character that is left in the stdin buffer from a previous input. The '\n' is consumed by scanf() and the program continues the execution.
You will need to clear the buffer before scanf() is executed.
Option 1 - Clear the buffer at the bottom of the while cycle:
//...
int c;
//...
else{
printf("Equal to 100.\n");
}
while((c = fgetc(stdin)) != '\n' && c != EOF){}
//...
Option 2 (simpler) - Use a space before %c specifier:
scanf(" %c", &input);
^
Try this : scanf(" %c", &input); (add space before %c)
scanf will likely take \n in buffer as input and placed in you character input.

Run-Time check failure #2 Stack around the variable 'optionAddress' was corrupted

I've been getting this error AFTER my program is done running, but before I get the 'Press any key to continue...' prompt. Here is my code
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "contacts.h"
int main (void)
{
// Declare variables here:
struct Name names;
char optionName;
struct Address addresses;
char optionAddress;
struct Numbers number;
char optionCell;
char optionHome;
char optionBusiness;
// Display the title
printf("Contact Management System\n");
printf("-------------------------\n");
// Contact Name Input:
printf("Please enter the contact's first name: ");
scanf ("%s", &names.firstName);
printf("Do you want to enter a middle initial(s)? (y or n): ");
scanf(" %c", &optionName);
while (optionName == 'y' || optionName == 'Y') {
printf("Please enter the contact's middle initial(s): ");
scanf("%s", &names.middleInitial);
break;
}
printf("Please enter the contact's last name: ");
scanf("%s", &names.lastName);
// Contact Address Input:
printf("Please enter the contact's street number: ");
scanf("%s", &addresses.streetNumber);
printf("Please enter the contact's street name: ");
scanf("%s", &addresses.street);
printf("Do you want to enter an apartment number? (y or n): ");
scanf("%s", &optionAddress);
while (optionAddress == 'y' || optionAddress == 'Y') {
printf("Please enter the contact's apartment number: ");
scanf("%s", &addresses.apartmentNumber);
break;
}
printf("Please enter the contact's postal code: ");
scanf("%s", &addresses.postalCode);
printf("Please enter the contact's city: ");
scanf("%s", &addresses.city);
// Contact Numbers Input:
printf("Do you want to enter a cell phone number? (y or no): ");
scanf("%s", &optionCell);
while (optionCell == 'y' || optionCell == 'Y') {
printf("Please enter the contact's cell phone number: ");
scanf("%s", number.cell);
break;
}
printf("Do you want to enter a home phone number? (y or n): ");
scanf("%s", &optionHome);
while (optionHome == 'y' || optionHome == 'Y') {
printf("Please enter the contact's home phone number: ");
scanf("%s", &number.home);
break;
}
printf("Do you want to enter a business phone number? (y or n): ");
scanf("%s", &optionBusiness);
while (optionBusiness == 'y' || optionBusiness == 'Y') {
printf("Please enter the contact's business phone number: ");
scanf("%s", number.business);
break;
}
I've looked through here to see how other people have fixed this issue but it seems like it's a memory issue or something and different for everyone. If I expand my program the error will not come until the code is finished. I've tried it without the "%s" and with " %c" instead, but when I do that the program skips the scanf's. If I've not provided enough information please let me know.
I've tried it without the "%s" and with " %c" instead, but when I do that the program skips the scanf's.
The reason behind stack corruption when you use %s is due to the null character (\0) which would be inserted after the single character. Since the size you have allocated for optionAddress is just a single character, you would be using more (at least two characters) than what you have allocated.
Therefore, using %c would be the right choice, and the skipping of scanfs would be probably due to the remaining newline characters in the input buffer. I'm not really sure which code will be able to fix this (Since I do not know how many scanfs are being skipped), but using getchar() to just remove a character(which could be a newline) from the input buffer, or using fflush(stdin) could help clearing the input buffer.
Using fflush(stdin) is not good practice though ,and even may not work depending on your environment. Just using " %c" like you did should usually solve the newline issue, but if it doesn't you could play around with getchar() until the scanfs are not skipped anymore.

Simple read/display C program outputs incorrect value while user inputs data

Can someone run the following C program on your IDE and advise me what I am missing?.
#include<stdio.h>
#include<conio.h>
int main()
{
int a;
char s;
char n[10];
printf("What is your name?: ");
scanf("%s", &n);
printf("What is your age?: ");
scanf("%d", &a);
printf("Are you male or female?: ");
scanf("%c", &s);
printf("Your name is %s\nYour age is %d\nYour sex is %c\n", n, a, s);
getch();
return 0;
}
While we enter the age and hit the enter button, it slips and shows wrong output without evening asking for the third input "Are you male or female?". I tested it on Turbo C++, Dev C++, Code Blocks, all show the same error output.
Your problem is that the scanf("%c", &s); takes the new-line character. Maybe you could try the following scanf(" %c", &s); (important ist the white-space before %c) as described here Problems with character input using scanf() or How to do scanf for single char in C
It would be correctly to write
printf("What is your name?: ");
scanf("%s", n);
^^^
or even
printf("What is your name?: ");
scanf("%9s", n);
instead of
printf("What is your name?: ");
scanf("%s", &n);
and
printf("Are you male or female?: ");
scanf(" %c", &s);
^^^
instead of
printf("Are you male or female?: ");
scanf("%c", &s);
Otherwise in the last case a white space character is read into the variable s.

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