Receiving Run-Time Check Failure #2 - c

I would like to ask why am i getting Run-time Check Failure #2 When i am doing my program?
I'm very new to C programming.
I'm trying to make a Console application that have some option after they key in Y/N,
But whenever i reach the end of all the option i get that error.
Could anyone tell me how i could solve it & what is the proper way of doing this kind of programming?
#define _CRT_SECURE_NO_WARNINGS // To allow Visual studio to use "scanf" function
#include <stdio.h> // Standard Input output . header
#include <Windows.h>
void codername() {
printf("Coder: Rong Yuan\n");
}
void projectname() {
printf("Project name: NPoly Learning\n");
}
void loadcurrentdate() {
SYSTEMTIME str_t;
GetSystemTime(&str_t);
printf("Date: %d . %d . %d \n"
, str_t.wDay, str_t.wMonth, str_t.wYear);
}
int main() {
char option;
int input;
int mincome, fmember, total;
printf("Do you like to see our option? Y/N \n");
scanf("%s", &option);
if (option == 'y' || option == 'Y') {
printf("1. Display Coder Detail\n");
printf("2. Display Project Name\n");
printf("3. Load Current Date\n");
printf("4. Calculator PCI\n");
printf("5. Exit\n");
scanf("%d", &input);
}
else
exit(1);
switch (input) {
case 1:
codername();
printf("Do you like to return to main?");
break;
case 2:
projectname();
break;
case 3:
loadcurrentdate();
break;
case 4:
printf("Enter your house monthly income: ");
scanf("%d", &mincome);
printf("Enter total family member: (INCLUDING YOURSELF) ");
scanf("%d", &fmember);
total = mincome / fmember;
printf("Total PCI: %d / %d = %d \n", mincome, fmember, total);
system("pause");
break;
case 5:
exit(0);
}
}

scanf("%s", &option);
is wrong as option is a char . So replace %s with %c there.%s should be used for strings (array of characters) and %c is the format specifier used for a character.

Related

While the program is on execution, the terminal ignores the presence of scanf()

So, I'm totally new to C and I'm having some struggle with some basic concepts, mainly when it is about buffer, memory, and string creation.
So, I have this assignment from College where I need to make an Array of Structs called Vehicles, and during the execution of the program I must take inputs from the user about the Vehicle mark, year, and licensePlate.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Vehicles {
char mark[20];
int modelYear;
char licensePlate[8];
};
int main() {
const int DEFAULT_SIZE = 10;
struct Vehicles vehiclesArr[DEFAULT_SIZE];
for(int i = 0; i < DEFAULT_SIZE ; i++) {
memcpy(vehiclesArr[i].mark, "", 1);
vehiclesArr[i].modelYear = 0;
memcpy(vehiclesArr[i].licensePlate, "", 1);
}
int choice = 0;
int counter = 0;
printf("Hello Professor, my name is Henrique and in this program I will be your guide.\n");
while (choice != 4) {
printf("So, what it will be for today?\n Choose a valid option.\n");
printf("0. Create a new Vehicle.\n");
printf("1. List all saved vehicles.\n");
printf("2. Update a saved vehicle.\n");
printf("3. Delete a saved vehicle.\n");
printf("4. Quit Program.\n");
scanf("%d", &choice);
switch (choice) {
case 0:
if (counter < 10) {
printf("Choose a vehicle mark \n");
scanf("%[^\n]s", vehiclesArr[counter].mark);
printf("\n Choose the model year \n");
scanf("%d", &vehiclesArr[counter].modelYear);
printf("\n Choose license plate \n");
scanf("%[^\n]s", vehiclesArr[counter].licensePlate);
counter++;
break;
} else {
printf("\n Storage limit reached.");
}
case 1:
for(int i = 0; i < DEFAULT_SIZE; i++) {
printf("\nModel: %s", vehiclesArr[i].mark);
printf("\nYear: %d", vehiclesArr[i].modelYear);
printf("\nLicense Plate: %s", vehiclesArr[i].licensePlate);
}
break;
case 2:
break;
case 3:
break;
case 4:
printf("Gently finishing program... Bye Bye!");
break;
default:
printf("\nWhat? The number must be between 0 and 4\n");
}
}
}
The problem is that, when I execute the program and press 0, the program just skip the user input on those two lines bellow:
...
printf("Choose a vehicle mark \n");
scanf("%[^\n]s", vehiclesArr[counter].mark);
...
printf("\n Choose license plate \n");
scanf("%[^\n]s", vehiclesArr[counter].licensePlate);
...
I'm trying to figure out what is happening been a while now, the only thing that works is if I use "%s", but I need the program to handle when user inputs an space character.
Can someone help me, and please explain why is this happening? This is my first question so I would appreciate if you guys also tell me how I can make my questions better.

I want to create a menu that shows 1. Client details, 2.Property details and 3. Exit

I want to create a menu that shows:
Client details
Property details
Exit
#include <stdio.h>
#include <conio.h>
void main() {
char L,F,H;
float CID,Aoc,Pte,Cost_per_sqft;
int dicnt,age,ch;
printf("Enter the Client ID\n");
scanf("%f", &CID);
printf("Enter the age of client\n");
scanf("%f", &Aoc);
if (age >=60) {
printf("The client is eligible for a discount\n");
} else if (age<60) {
printf("The client is not eligible for a discount\n");
} {
printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf("%f", &Pte);
}
printf("Please select the menu option\n");
printf("1.Client ID\n");
printf("2.Property details\n");
printf("3.Exit\n");
scanf("%d", &ch);
switch(ch) {
case 1:
printf("Client ID %f", CID);
printf("Age of client %f", Aoc);
}
}
It's not letting me enter the option to open a menu, also the age else is doesn't work because age => 60 is also showing not eligible for discount. The switch case doesn't work either.
Problem 1 is that you have defined two variables, float Aoc and int age, then attempt to use them interchangeably. Also, the first time age is referenced ( here: if (age >=60) ) it is uninitialized, which contributes to the problems you have described.
Addressing the following will fix the if-else statement for age, and will allow the menu to appear...
Since age is typically a non-float value, i.e. 45 or 50, but never expressed as 45.5.
Suggest replacing, Aoc everywhere it exists with age, (modifying the format specifiers accordingly), and finally, initialize age before use.
Problem 2 is here:
...
{ printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf("%f", &Pte);
You are prompting user to input a char value, then attempt to read it in into a float variable Pte. Suggest if desiring to read in as a char, use a " %c" format specifier, and change float Pte to char Pte.
(Note space in format specifier, it is there for this reason.)
{ printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf(" %c", &Pte);//note space in front of %c to consume newline
Working code adapted from your original:
void main()
{
char L,F,H;
float CID,Aoc;/*Pte*/
float Cost_per_sqft;
int dicnt,age,ch;
char Pte;
printf("Enter the Client ID\n");
scanf("%f", &CID);
printf("Enter the age of client\n");
scanf("%d", &age);
if (age >=60)
{
printf("The client is eligible for a discount\n");
}
else if (age<60)
{
printf("The client is not eligible for a discount\n");
}
{ printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf(" %c", &Pte);
}
printf("Please select the menu option\n");
printf("1.Client ID\n");
printf("2.Property details\n");
printf("3.Exit\n");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("Client ID %f\n", CID);
printf("Age of client %d", age);
break;
case 2:
;//add content
break;
case 3:
;//add content
break;
}
}

I'm trying to make a menu in C and my code is not working the way I want it to

I'm working on an assignment for my programming class and the first thing I tackled is of course to make the main menu. But for some reason, the program is not working the way I intend it to.
#include <stdio.h>
#include <stdlib.h>
void mainMenu();
void firstChoice();
int main()
{
int main_menu_choice;
int _1returnMenu;
mainMenu();
scanf("%d", &main_menu_choice);
while (main_menu_choice != 0){
switch(main_menu_choice){
case 1:
firstChoice();
scanf("%d", &_1returnMenu);
while (_1returnMenu != 0){
switch (_1returnMenu){
case 1:
firstChoice();
scanf("%d", &_1returnMenu);
break;
case 0:
mainMenu();
scanf("%d", &main_menu_choice);
break;
default:
printf("Invalid option, please try again: \n");
scanf("%d", &_1returnMenu);
break;
}
}
break;
case 0:
exit(0);
default:
printf("Invalid option, please try again: \n");
scanf("%d", &main_menu_choice);
}
}
return 0;
}
void firstChoice(){
printf("Enter the necessary information \n");
printf("Please enter the student's ID: \n");
scanf("%d", &student.id);
printf("Please enter the student's name: \n");
scanf("%s", student.name);
printf("Please enter the gender of the student: \n");
scanf("%s", student.gender);
printf("Please enter the details of the room: \n");
scanf("%s", student.roomDetails);
printf("Please enter the amount due of the student: \n");
scanf("%d", &student.amountDue);
printf("Please enter the amount paid by the student: \n");
scanf("%d", &student.paymentMade);
printf("Do you want to store another hosteler's information? \n");
printf("Type 1 if you wish to continue, Type 0 to go back to the main menu: \n");
return;
}
void mainMenu(){
printf("Welcome! This program will help you in managing the hostel booking
of Wisdom College \n");
printf("Type the number of your option: \n");
printf("1. Store details of hosteler \n");
printf("2. Check room availability \n");
printf("3. Payment Facility \n");
printf("4. Search room details of hosteler \n");
printf("5. To cancel booking of a hosteler \n");
printf("6. Change room type \n");
printf("0. Exit the program \n");
return;
}
Okay so when I run the program and I choose the first option which is "1.Store details of hosteler" then just put on some random information and after inputting the required info the program will ask me if I want to continue using it or not. If I press 1 it will ask me to fill up the required information again and if I press 0 it should go back to the main menu.
But the thing is, when I type in 0 it doesn't go back to the main menu, instead it just runs the firstChoice() function again instead of running the case 0 in the switch statement. I've been scratching my head for 2 hours trying to figure out what's wrong but I just cant seem to find what's wrong. I'm so sorry if I wasn't able to word my problem properly, and thanks in advance!
the following proposed code shows how to write the menu display and handling
int done = 0;
while( !done )
{
mainMenu();
if( scanf("%d", &main_menu_choice) != 1 )
{
fprintf( stderr, "scanf for menu choice failed\n" );
exit( EXIT_FAILURE );
}
switch(main_menu_choice)
{
case 0:
done = 1;
break;
case 1:
firstChoice();
break;
case 2:
checkRoomAvalability();
break;
case 3:
paymentFacility();
break;
case 4:
switchRoomDetails();
break;
case 5:
cancelBooking();
break;
case 6:
changeRoomType();
break;
default:
puts("Invalid option, please try again: \n");
break;
}
}
void mainMenu()
{
puts( "Welcome!"
" This program will help you in managing"
" the hostel booking of Wisdom College \n"
"Type the number of your option: \n"
"1. Store details of hosteler \n"
"2. Check room availability \n"
"3. Payment Facility \n"
"4. Search room details of hosteler \n"
"5. To cancel booking of a hosteler \n"
"6. Change room type \n"
"0. Exit the program \n" );
}

How to make getchar() read a negative number?

I am writing a program that can calculate the areas of a square, cube, and circle. The program needs to present an error message and allow the user to enter a new choice if they enter something not included in the menu. My problem is that if they type anything includes my menu options then the program still executes. (i.e. -1, 23, 344) I was wondering how to get it to ignore anything after the first character or to read the whole string. Or if there is something better than getchar(). I'm open to any solutions! Thank you!
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int choice;
int lengthsq;
int areasq;
int lengthcube;
int areacube;
int radius;
double circlearea;
printf("Area Calculation\n");
printf("(1) Square\n");
printf("(2) Cube\n");
printf("(3) Circle\n");
fputs("Please make a selction: ", stdout);
while((choice = getchar()) != '\n')
switch (choice) {
case '1':
printf("\nPlease enter the length: ");
scanf("%d", &lengthsq);
while(lengthsq <= 0){
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthsq);
}
areasq = lengthsq * lengthsq;
printf("The area of the square is %d.", areasq);
return 0;
case '2':
printf("\nPlease enter the length: ");
scanf("%d", &lengthcube);
while (lengthcube <= 0) {
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthcube);
}
areacube = 6 * lengthcube * lengthcube;
printf("The surface area of the cube is %d.\n", areacube);
return 0;
case '3':
printf("\nPlease enter the radius: ");
scanf("%d", &radius);
while(radius <= 0){
printf("Error! Pleae enter a postive number: ");
scanf("%d", &radius);
}
circlearea = 3.14159 * radius * radius;
printf("The area of the circle is %.2f.\n", circlearea);
return 0;
case '\n':
case '\t':
case ' ':
break;
default:
printf("\nInvalid choice entered.\n");
fputs("Enter a new choice: ", stdout);
break;
}
}
You could add another switch case for the dash, which would toggle some kind of negative flag and then read a number as you're already doing. If you do not like introducing such a flag, then the best option would be using fgets, which returns the entire input line. But that has the downside that you need to parse the input. I.e. do some string manipulation, which may be slightly more complex than a simple flag parameter.
On the other hand, from the code you attached, I deduct that the only valid input consists of mere numbers (integers). You could just read an integer then with scanf.

undeclared identifier in C

I am trying to compile a small bank program in C in visual studio 2012 express. It shows me this error "undeclared identifier" for almost all variables and this one too "syntax error: missing ';' before 'type'".Please tell me the correct syntax.Thank you.
#include<stdio.h>
#include<conio.h>
int main()
{
printf("Welcome to skybank\n");
int deposit,withdraw,kbalance;
char option;
printf("Press 1 to deposit cash\n");
printf("Press 2 to Withdraw Cash\n");
printf("Press 3 to Know Your Balance\n");
scanf_s("%c",option);
int decash,wicash;
switch(option)
{
int balance;
printf("Enter your current Balance\n");
scanf_s("%d",&balance);
case 1:
printf("Enter the amount you want to deposit\n");
scanf_s("%d",&decash);
printf("Thank You\n");
printf("%d have been deposited in your account\n",decash);
break;
case 2:
printf("Enter the amount you want to withdraw\n");
scanf_s("%d",&wicash);
int wibal;
wibal=balance-wicash;
printf("Thank You\n");
printf("%d have been withdrawed from your account\n",wicash);
printf("Your balance is %d\n",wibal);
break;
case 3:
printf("Your balance is Rs.%d\n",balance);
break;
default:
printf("Invalid Input\n");
break;
}
getchar();
}
The Microsoft C compiler only supports a 25 year old version of the language. And one of the limitations is that all variables must be declared before any other statements. So move all your variable declarations to the top of the function.
The next error I can see is the use of scanf_s with the %c format string. You must pass a pointer to the variable, and pass the number of characters to read.
scanf_s("%c", &option, 1);
And likewise you need to pass an address for the read of balance.
You also need to change the switch statement so that it just contains cases. Move the bare instructions outside.
Your reading of option won't work. Because when you check for 1 you are checking for the character with ASCII code 1. Change option to be an int and read using %d.
Perhaps you are looking for something like this:
#include<stdio.h>
#include<conio.h>
int main(void)
{
int deposit,withdraw,kbalance;
int option;
int decash,wicash;
int balance;
int wibal;
printf("Welcome to skybank\n");
printf("Press 1 to deposit cash\n");
printf("Press 2 to Withdraw Cash\n");
printf("Press 3 to Know Your Balance\n");
scanf_s("%d", &option);
printf("Enter your current Balance\n");
scanf_s("%d", &balance);
switch(option)
{
case 1:
printf("Enter the amount you want to deposit\n");
scanf_s("%d", &decash);
printf("Thank You\n");
printf("%d have been deposited in your account\n", decash);
break;
case 2:
printf("Enter the amount you want to withdraw\n");
scanf_s("%d", &wicash);
wibal=balance-wicash;
printf("Thank You\n");
printf("%d have been withdrawed from your account\n", wicash);
printf("Your balance is %d\n", wibal);
break;
case 3:
printf("Your balance is Rs.%d\n", balance);
break;
default:
printf("Invalid Input\n");
break;
}
getchar();
}
Regarding the unidentified variables, try putting all declarations of variables at the top of the main block, something like:
int main()
{
int deposit, withdraw, kbalance, decash, wicash, wibal;
char option;
printf("Welcome to skybank\n");
Older variants of C frown upon mixing variable declarations with code. To my knowledge the C standard of Microsoft's C implementation is pre-C99 so perhaps this could be the issue.
A few other issues that you should look into:
scanf_s("%c",option); - option should be &option as you are taking a pointer to that variable.
Also here: case 1:
You want '1' (as in case '1') instead of plain 1 as it is a char, not an int you want.
Same for the other case checks.
With regards to the scanf_s problems, try compiling with warnings, it should have been pointed out by the compiler.
Finally, you might want to rid your code of the variables you're not using such as kbalance, withdraw and deposit.
do at the beginning of the block in the declaration of the variable for visual c.
E.g.
int main()
{
int deposit,withdraw,kbalance;
char option;
int decash,wicash
int balance;
int wibal;
...
try this code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("Welcome to skybank\n");
int deposit,withdraw,kbalance;
char option;
printf("Press 1 to deposit cash\n");
printf("Press 2 to Withdraw Cash\n");
printf("Press 3 to Know Your Balance\n");
scanf("%c",&option);
int decash,wicash;
switch(option)
{
int balance;
printf("Enter your current Balance\n");
scanf("%d",&balance);
case 1:
printf("Enter the amount you want to deposit\n");
scanf("%d",&decash);
printf("Thank You\n");
printf("%d have been deposited in your account\n",decash);
break;
case 2:
printf("Enter the amount you want to withdraw\n");
scanf("%d",&wicash);
int wibal;
wibal=balance-wicash;
printf("Thank You\n");
printf("%d have been withdrawed from your account\n",wicash);
printf("Your balance is %d\n",wibal);
break;
case 3:
printf("Your balance is Rs.%d\n",balance);
break;
default:
printf("Invalid Input\n");
break;
}
getchar();
}
Move this:
int balance;
printf("Enter your current Balance\n");
scanf_s("%d",&balance);
Before the switch statement.

Resources