C: Multiple input from keyboard - c

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.

Related

How to read three variables using scanf in C?

I am writing a simple calculator. I want to read first integer and save it in el1. Then I want to print "Enter el2: \n" and after this read the second integer and save it in el2. After this I need to print "Choose from ( + , - , / , * )" and read it and save in op[0]. My program is printing Enter el1: and then it waits for me to input 2 integers, then it pronts Enter el2: and waits for me to input 1 integer and then prints Choose from.. and reads nothing.
int el1 = 0;
printf("Enter el1: \n");
scanf(" %d \n", &el1);
int el2 = 0;
printf("Enter el2: \n");
scanf(" %d \n", &el2);
printf("Choose from ( + , - , / , * ):\n");
char op[2];
scanf("%c", &op[0]);
How to make it work properly?
as mentioned in comments remove white spaces from scanf .otherwise it will wait for you to enter a non-white space character.
and add one space here scanf(" %c", &op[0]); , because it prevent scanf to take \n in buffer as input.
look
printf("Enter el1: \n");
scanf("%d", &el1);
int el2 = 0;
printf("Enter el2: \n");
scanf("%d", &el2);
printf("Choose from ( + , - , / , * ):\n");
char op[2];
scanf(" %c", &op[0]);

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.

C programming simple issue .Asking two Inputs on same line

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.

Trouble with scanf

Trying to get some values to a struct. When I run the code, everything works perfectly except for the Gender values. For some reason that whole scanf just gets skipped over. In the command prompt it looks like this.
Please provide the student's first name: (user enters "John" and presses enter)
Please provide the student's first name: (user enters "Doe" and presses enter)
Please provide the student's gender (M/F): (can't input anything, no line skip) Please provide the student's age: (input)
etc.
I don't know if this could be a problem with another portion of the program, but I can edit in the whole thing if the problem isn't within this chunk of code.
if (option == 2){
i=i+1;
printf("Please provide the student's first name: ");
scanf("%s", roster[i].firstname);
printf("Please provide the student's last name: ");
scanf("%s", roster[i].lastname);
printf("Please provide the student's gender (M/F): ");
scanf("%c", &roster[i].gender);
printf("Please provide the student's age: ");
scanf("%i", &roster[i].age);
printf("Please provide the student's weight (In pounds): ");
scanf("%i", &roster[i].weight);
printf("Please provide the student's height (In inches): ");
scanf("%i", &roster[i].height);
}
The problem here is that the code that reads the last name reads up to but not including the newline at the end of the input, and the %c conversion specification does not skip leading white space, so the gender input reads a newline into the gender and continues on to the next prompt (age).
Use " %c" to skip white space (which includes blanks, tabs and newlines) before reading a non-space character.
I note in passing that you should be checking each of your scanf() calls to ensure it recognized the input.
printf("Please provide the student's first name: ");
if (scanf("%s", roster[i].firstname) != 1)
...handle error...
printf("Please provide the student's last name: ");
if (scanf("%s", roster[i].lastname) != 1)
...handle error...
printf("Please provide the student's gender (M/F): ");
if (scanf("%c", &roster[i].gender) != 1)
...handle error...
printf("Please provide the student's age: ");
if (scanf("%i", &roster[i].age) != 1)
...handle error...
printf("Please provide the student's weight (In pounds): ");
if (scanf("%i", &roster[i].weight) != 1)
...handle error...
printf("Please provide the student's height (In inches): ");
if (scanf("%i", &roster[i].height) != 1)
...handle error...
Also, pity the student with spaces in the surname, or even forename.

Resources