Need help about inputting strings and printing it out - c

I am stuck on a part of an assignment I am writing.
When I am typing in the postalCode (which is A8A 4J4) it shows
It is supposed to be:
Postal code: A8A 4J4
City: Toronto
It is skipping the option to enter the City.
I've tried %[^\n] and it still skips the option to enter the City.
My current code is:
if (option == 'y' || option == 'Y') {
printf("Please enter the contact's apartment number: ");
scanf("%u", &address.apartmentNumber);
printf("Please enter the contact's postal code: ");
scanf("%s", &address.postalCode);
}
if (option == 'n' || option == 'N') {
printf("Please enter the contact's postal code: ");
scanf("%s", &address.postalCode);
}
printf("Please enter the contact's city: ");
scanf("%40s", address.city);
printf("Postal code: %s\n", address.postalCode);
printf("City: %s\n", address.city);
I saw a post about this already but the answers there didn't help. I already tried the [^\n] in my scanf.

The better for string input is fgets as scanf ("%[^\n]%*c", &address.city); does not work well if the the line is only "\n" or too long. Stick with fgets().
fgets(address.city,40,stdin);
EDIT: If you still want to use scanf use like this
scanf (" %[^\n]%*c", &address.city)
it will scan characters until it finds '\n'

Put the & on your reference to address.city
like this
scanf("%40s", &address.city);

Related

Program crashing near the end of compiling

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

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.

C: Multiple input from keyboard

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.

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