C code crashes (no idea why) - c

Basically I'm a beginner coder and this is what I wrote:
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("COLOR 0A");
char playerName[13];
char playerGender;
int playerAge;
printf("Please input your name and age!\nName: ");
scanf("%s", playerName);
printf("Age (from 18 to 50): ");
scanf("%d", &playerAge);
label:
if(playerAge > 18 && playerAge < 50)
{
printf("What gender are you, M(male) or F(female): ");
scanf("%c", playerGender);
gender:
if(playerGender == 'M' || playerGender == 'F'){
printf("Okay, so your name is %s, you're %d years old and you're a %s.", playerName, playerAge, playerGender);
}else{
printf("Try again.\n\n"
"What gender are you, M(male) or F(female): ");
scanf("%c", playerGender);
goto gender;
}
}else{
printf("Wrong, try again.\n"
"Age (from 18 to 50): ");
scanf("%d", &playerAge);
goto label;
}
return 0;
}
When I put the required age to continue, it crashes on the scanf for the playerGender. Right after it shows me the question about my gender? Where is my mistake?

try:
scanf("%c", &playerGender);
instead of
scanf("%c", playerGender);
as scanf takes a pointer and not a reference to the variable you are trying to fill.

I am also beginner but I think that you need to write thisscanf("%s", playerName); like thisscanf("%12s", playerName);
BTW let me know if that works.

Related

C Program Printing Wrong Message | Logical Operator Problem?

I am new to coding in C and trying to write a program that prints the message 'You may enter' if your age is 15 or over, and your gender is equal to male. Kindly see what I've got below. When you enter your age as 15 or over and your gender as male, the program prints the wrong message. I think it could be a problem with my logical operators but I can't quite figure out why. Could you assist?
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int age;
char gen;
printf("How old are you?\n");
scanf("%d", &age);
printf("What is your gender? (m/f) \n");
scanf("%s", &gen);
if(age >= 15 && gen == 'm')
{
write(1, "You man enter\n", 15);
}
if(age < 14 || gen == 'f')
{
write(1, "No entry\n", 9);
}
return 0;
}
Change this:
scanf("%s", &gen);
to this:
scanf(" %c", &gen);
since gen is a character, not a string.
Note the space I left before the format specifier for characters, which is there to inform the method to automatically eat whitespaces and special characters (remove it and see what happens). For more, ready my initial reaction to this Caution when reading char with scanf (C).
Thanks #gsamaras!
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int age;
char gen;
printf("How old are you?\n");
scanf("%d", &age);
printf("What is your gender? (m/f) \n");
scanf(" %c", &gen);
if(age >= 15 && gen == 'm')
{
write(1, "You may enter\n", 15);
}
if(age <= 14 || gen == 'f')
{
write(1, "No entry\n", 9);
}
return 0;
}

A nesting 'if' statement does not work [duplicate]

This question already has answers here:
fgets doesn't work after scanf [duplicate]
(7 answers)
Why does a space in my scanf statement make a difference? [duplicate]
(3 answers)
Closed 5 years ago.
I'm trying to code very simple code, and here it is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int age;
char gender;
printf("How old are you? \n");
scanf("%d", &age);
printf("What is your gender? (m/f) \n");
scanf("%c", &gender);
if ((age >= 18 && gender == 'm')){
printf("You may enter this website ");
if (age <= 20)
{
printf("dude.");
}
}
if ((age >= 18 && gender == 'f')) {
printf("You may enter this website ");
if (age <= 20)
{
printf("young lady.");
}
}
else if (age < 18)
{
printf("Nothing to see here! \n");
}
return 0;
}
In the code above, I'm trying to use a nesting if statement. But it doesn't work, not as I wish. After I enter the age, it prints out the sentence: What is your gender? (m/f).
When the second sentence is printed out, it terminates. But I don't know why.
I want the user be able to enter the gender and based on the entered gender and age it should print out a sentence.
Could you please give me a hint?
There is nothing wrong with the logic of your code, so the most likely reason for the behavior that you see is this line:
scanf("%c", &gender);
Since the line follows reading of an int, the '\n' that remains in the buffer gets assigned to gender immediately.
You can fix this by adding a space in front of %c to ignore newline:
scanf(" %c", &gender);
You can also reduce the code somewhat by combining a few checks:
if (age >= 18){
printf("You may enter this website ");
if (age <= 20) {
printf("%s.\n", gender == 'm' ? "dude" : "young lady");
}
}
Replace scanf("%c", &gender) with scanf(" %c", &gender)
This is because when you enter your age and press enter key, your age will be stored in age variable but '\n'(enter key) is still present in the buffer which will be read by the gender.
So, you can do these things-
scanf("%d\n",&age)
or
use
scanf("%d", &age);
getchar();

How to compare strings with user input?

I have a question in my paper. I have 10 employee ids M001,A004,D007,etc...User is inputting one of the the mentioned Ids and if the id is not there it prints id not found. I tired with strcmp and got stuck. Its good if you tell me a way to do it? Thanks, note: i am a beginner in C.I am trying an easy way now it gives the error with the for loop.
subscripted value is neither array nor pointer nor vector
#include<stdio.h>
#include<string.h>
float tSalary(float salary,float bonus);
char searchid(char search);
int main(void)
{
char status,input,search,C,P;
char searchId[8][4]={"M001","A004","D007","D010","D012","Q008","Q015","DE09"};
float salary,bonus,tSalary;
int i,j;
do{
printf("Enter the employee id: ");
scanf("%s", &search);
printf("Enter the job status: ");
scanf("%s", &status);
printf("Enter the salary: ");
scanf("%f", &salary);
for(i=0;i<8;i++){ //This is where all things go wrong
for(j=0;j<4;j++){
if(searchid[i][j]=search){ //the [i] where the subscripted error occurs
printf("Id is valid\n");
}
else printf("Invalid id\n");
}
}
printf("Do you want to enter another record?(Y-Yes/N-No): ");
scanf(" %c", &input);
}while(input=='Y'||input=='y');
return 0;
}
There are quite a few problems in the posted code. For starters, searchId should be declared as searchId[8][5], to make room for the \0 terminator at the end of each string.
It appears from the input code that status and search should hold strings, but these are declared as chars. After fixing this, note that there is no need for the address operator & in the calls to scanf() that read into these arrays. Also, maximum widths should always be specified when using the %s conversion specifier with scanf() to avoid buffer overflows.
Strings can not be compared using the == comparison operator, so strcmp() should be used here. This can be done in a loop that steps through the array of strings; the loop exits when the index reaches 8, or a comparison is successful. Then, after the loop, if the index has reached 8 (all valid id strings failed the test) the search string was not valid.
Here is a modified version of the posted code that implements all of this:
#include <stdio.h>
#include <string.h>
float tSalary(float salary,float bonus);
char searchid(char search);
int main(void)
{
char status[1000];
char search[1000];
char input, C, P;
char searchId[8][5] = { "M001", "A004", "D007", "D010",
"D012", "Q008", "Q015", "DE09" };
float salary, bonus, tSalary;
int i, j;
do {
printf("Enter the employee id: ");
scanf("%999s", search);
printf("Enter the job status: ");
scanf("%999s", status);
printf("Enter the salary: ");
scanf("%f", &salary);
i = 0;
while (i < 8 && strcmp(search, searchId[i]) != 0) {
++i;
}
if (i < 8) {
printf("Id is valid\n");
} else {
printf("Invalid id\n");
}
printf("Do you want to enter another record?(Y-Yes/N-No): ");
scanf(" %c", &input);
} while (input == 'Y' || input == 'y');
return 0;
}
Sample program interaction:
Enter the employee id: A004
Enter the job status: pending
Enter the salary: 2000
Id is valid
Do you want to enter another record?(Y-Yes/N-No): y
Enter the employee id: Q015
Enter the job status: completed
Enter the salary: 3000
Id is valid
Do you want to enter another record?(Y-Yes/N-No): y
Enter the employee id: B001
Enter the job status: completed
Enter the salary: 1200
Invalid id
Do you want to enter another record?(Y-Yes/N-No): n

Program does not exit when expected

I'm new to C and I am trying to write a program that will let you enter up to 100 people's age and salary. The program at first will print some sentences to introduce (the display function) and then ask you whether you want to continue or not (yes_no function). After you enter a person's information, the program will also ask if you would like to continue to enter the next person's information or not. If you would like to continue, you will need to enter 1 and 0 for no/exit. When I compile and run the code, I found a problem and i could not figure out why!
The problem is that if you choose 0 (which means no/exit) after entering one's information, the program does not exit. It instead just asks the next person's information. But when I choose 0 right from the beginning, it just exits like usual. Why?
#include<stdio.h>
#define max 100
#define yes 1
#define no 0
int display(void);
int yes_no(void);
void get_data(void);
int date[max],month[max],year[max];
int cont;
int salary;
int main(){
cont=display();
if (cont==yes){
get_data();
}
return 0;
}
int display(void){
printf("This program will let you enter ");
printf("the age and salary of up to 100 people ");
cont=yes_no();
return cont;
}
int yes_no(void){
int i=0;
printf("\nDo you want to continue? Enter 1 for Yes and 0 for No\n");
scanf("%d", &i);
while(i<0 || i>1){
printf("Invalid value.Please enter again\n");
scanf("%d", &i);
}
if(i==1){
return (yes);
}else return (no);
}
void get_data(void){
int i=0;
for(i=0;i<max;i++){
printf("Enter information for people %d\n", i+1);
printf("Enter birthday\n");
do{
printf("Enter date\n");
scanf("%d", &date[i]);
}while( 0>date[i] || 31<date[i] );
do{
printf("Enter month\n");
scanf("%d", &month[i]);
}while( 0>month[i] || 12<month[i]);
do{
printf("Enter year\n");
scanf("%d", &year[i]);
}while( 1900>year[i] || 2016<year[i]);
printf("Enter salary\n");
scanf("%d", &salary);
cont=yes_no();
}
}
void get_data(void){
int i=0;
for(i=0;i<max;i++){
printf("Enter information for people %d\n", i+1);
printf("Enter birthday\n");
do{
printf("Enter date\n");
scanf("%d", &date[i]);
}while( 0>date[i] || 31<date[i] );
do{
printf("Enter month\n");
scanf("%d", &month[i]);
}while( 0>month[i] || 12<month[i]);
do{
printf("Enter year\n");
scanf("%d", &year[i]);
}while( 1900>year[i] || 2016<year[i]);
printf("Enter salary\n");
scanf("%d", &salary);
cont=yes_no(); // <== The Problem lies here
}
}
You ask the user if wants to continue but you never check the return value of yes_no()
Just add this after this line and it should work like a charm:
if (cont == no)
return;
As others have mentioned, there are still some things you can do to "improve" your code.
defines should be capitalized so #define YES 1 would stick to this convention.
And you shouldn't use global variables. These are bad programming style. Simply pass the things you need in other functions as a parameter and if you need the manipulated value later on past them as a pointer.
Also the formatting could be improved (however this is a mostly opinion based topic ;) )
In C you usually have an extra line for each curly bracket.
void get_data(void)
{
...
}
//instead of
void get_data(void){
...
}
Also the blanks after the do-while-loop should look more like so:
do
{
...
} while(1900 > year[i]); //here the curly bracket is ok that way
And operators should have a blank on both sides:
printf("Enter information for people %d\n", i + 1);
// instead of this
printf("Enter information for people %d\n", i+1);
This is all I've seen up to now.

In C: 2 printf output when all I want is one.

This program is supposed to balance an account by asking for original amount then asking what sort of transaction they would like. The printf call is called twice when all I want is one. output: "Enter transaction: Enter transaction: ". Otherwise works fine. code:
#include <stdio.h>
int main(void)
{
float amount, old, new;
char letter;
printf("Please enter your current balance: ");
scanf("%f", &old);
printf("Enter the kind of transaction you would like: W - withdrawl, D - deposit, F - finished. \n");
scanf("%c", &letter);
while (letter != 'F'){
if (letter == 'D'){
printf("Amount: ");
scanf("%f", &amount);
new = old + amount;
old = new;
}
if (letter == 'W'){
printf("Amount: ");
scanf("%f", &amount);
new = old - amount;
old = new;
}
printf("Enter transaction: ");
scanf("%c", &letter);
}
if (letter == 'F')
printf("Your ending balance is %f.\n", old);
return 0;
}
Would greatly appreciate any insight! Thank you!!
scanf(" %c", &letter); instead of scanf("%c", &letter);
the original (without space) would interpret Enter as an input.
You may also be able to solve the issue by clearing the input (previous Enter press) from stdin input buffer. Add this line
fflush(stdin);
before
scanf("%c", &letter);
However, the solution provided by #artm is recommended, mine might not work depending on platform.

Resources