Hello i am beginner in programmin. I have simple issue. When i take user input. I was asked
Enter Your Age:
then after entering age i was asked(problem is here: why it's executing two linesc)
"Enter c for city and v for village: Enter 'h' for healthy and 'p' for poor health: "
and cursor comes after health:
It should ask for "Enter c for city and v for village:" first. I have tried alot. Please help me
int main(){
int age;
char sex;
char location;
char health;
printf("Enter Your Age: ");
scanf("%d",&age);
printf("Enter c for city and v for village: ");
scanf("%c", &location);
printf("Enter 'h' for healthy and 'p' for poor health: ");
scanf("%c", &health);
printf("Enter 'm' for male and 'f' for female: ");
scanf("%c", &sex);
if(age>=25 && age<=35){
printf("hello ahmed ");
}
else{
printf("Sorry You Cannot Be Insured ");
}
getch();
return 0;
}
It seems when you enter your age, the 'enter' remains in the buffer and gets read into location.
printf("Enter Your Age: ");
scanf("%d",&age);
printf("Enter c for city and v for village: ");
scanf("\n%c", &location); // add this line to ignore the newline character.
EDIT: fflush() removed because it seems it works only for output streams and not input. IMO Better is to first read the newline character and then the actual location character.
Another option is to
scanf(" %c", &location);
include a space before the %c for it to ignore the white space or new line.
Related
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.
I've got a program for taking input and storing it into structs. The structs are for contact details, Name, Address, and Phone numbers. My program works just fine, I can enter all my information into the program however when I try to printf the results the program crashes halfway through. I think they may be an issue with memory or corruption, or something. The reason I think it may be with corruption is because if I cut off some of my program and compile it, instead of the program crashing I get a 'Run-Time check failure #2 Stack around the variable 'optionAddress' was corrupted' error. Here's my program
#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("%s", &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(" %c", &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(" %c", 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(" %c", &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(" %c", number.business);
break;
}
// Display Contact Summary Details
printf("Contact Details\n");
printf("---------------\n");
printf("Name Details\n");
printf("First name: ");
printf("%s", names.firstName);
printf("\nMiddle initials(s): ");
printf("%s", names.middleInitial);
printf("\nLast name: ");
printf("%s", names.lastName);
printf("\n\nAddress Details\n");
printf("Street number: ");
printf("%s", addresses.streetNumber);
printf("\nStreet name: ");
printf("%s", addresses.street);
printf("\nApartment: ");
printf("%s", addresses.apartmentNumber);
printf("\nPostal code: ");
printf("%s", addresses.postalCode);
printf("\nCity: ");
printf("%s", addresses.city);
printf("\n\nPhone Numbers: ");
printf("\nCell phone number: ");
printf("%s", number.cell);
printf("\nHome phone number: ");
printf("%s", number.home);
printf("\nBusiness phone number: ");
printf("%s", number.business);
// Display Completion Message
printf("\n\nStructure test for Name, Address, and Numbers Done!");
return 0;
}
And the structs in the header file:
// Structure type Name declaration
struct Name {
char firstName[31];
char middleInitial[7];
char lastName[36];
};
// Structure type Address declaration
// Place your code here...
struct Address {
char streetNumber;
char street[41];
char apartmentNumber;
char postalCode[8];
char city[41];
};
// Structure type Numbers declaration
// Place your code here...
struct Numbers {
char cell[21];
char home[21];
char business[21];
};
My program reaches the point of printing out "Street number: " then stops working. It is a windows error window that shows up, not a compiler window.
My program reaches the point of printing out "Street number: " then
stops working.
Take a look at:
struct Address {
char streetNumber; // declared as character!
char street[41];
char apartmentNumber; // character
char postalCode[8];
char city[41];
};
char optionName;
char optionAddress;
char optionCell;
char optionHome;
char optionBusiness;
Later on you try to read the values to the characters:
scanf("%s", &optionName);
scanf("%s", &optionAddress);
scanf("%s", &optionCell);
scanf("%s", &optionHome);
scanf("%s", &optionBusiness);
scanf("%s", &addresses.streetNumber); // <-------------- string read
using string format %s. That invokes UB since you are reading at least 2 bytes. "y" is a string with string null terminator '\0'. That extra byte overwrites the memory location.
Change declarations of variables to strings or reading format to character read as you already do here:
scanf(" %c", &addresses.apartmentNumber);
scanf("%s", &optionName);
This invites undefined behavior which could lead to run time error you are getting as optionName is char one byte and scanf() with %s will try to write '\0' which will surely go beyond bounds
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.
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.
I'm trying to read multiple input from keyboard and store the input in variables.
A snipet of my code:
char answer = 'N';
int artnr;
char artname [27];
int stock;
double price;
while (answer != 'Y') {
printf("%s\n", "Enter article number:");
scanf("%d" , &artnr);
printf("%s\n", "Enter article name:");
scanf("%c" , &artname);
printf("%s\n", "Enter stock balance:");
scanf("%d" , &stock);
printf("%s\n", "Enter a price");
scanf("%f" , &price);
printf("%s\n", "Do you want to quit? (Y/N)");
scanf("%c" , &answer);
}
Output:
Enter article number:
1
Enter article name:
Enter stock balance:
25
Enter a price
4
Do you want to quit? (Y/N)
Enter article number:
Something seems to go wrong with my scanning. I guess it has to with the '/o' in the article name or when I press enter in order to confirm my input.
artname is a char array and "Enter article name:" suggests you actually wanted to scan a string.
So, this
scanf("%c" , &artname);
probably should be
scanf("%s", artname);
scanf() leaves the trailing newline when you scan with %c in the input buffer. You can ignore it by adding a whitespace in the format string:
scanf("%c" , &answer);
to
scanf(" %c" , &answer); // Notice the space in " %c"
A whitepsace in the format string tells scanf() to ignore any number of whitespaces in the input.
and change this
scanf("%f" , &price);
to
scanf("%lf" , &price);
in order to match the format string with the type.