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;
}
Related
Every time I run the program, the last "if" statement is not working, it means if I type "no", the loop won't break. Can someone please help me here?
#include <stdio.h>
int main() {
int age, i;
char ans;
for (i = 0; i < 3; i++) {
printf("\n enter your age:");
scanf("%d", &age);
if (age > 18) {
printf("your age is %d, you are allowed to enter", age);
} else if (age == 18) {
printf("I don't know what to do with you");
} else {
printf("your age is %d, you are not allowed to go in", age);
}
printf("\n continue?");
scanf(" %c", &ans);
if (ans == 'no') { // <-- here
break;
} else {
continue;
}
}
return 0;
}
use if (ans == 'n'). If you want to use the word "no", you have to change the type of variable ans to char array and use strcmp() method to compare strings.
In c programming single quotes (i.e. 'c') are used for characters and double quotes (i.e. "c") are used for strings. In double quotes last character is NULL.
Note: We cannot keep two characters in single quote like 'no'.
In your case first thing, declare ans as character array(i.e. string).
char ans[SIZE_AS_PER_REQUIREMENT];
To take input in this,
scanf("%s",ans);
For a better user experience before taking input give a proper message to user.
printf("\n Do you want to continue(yes/no)?");
Now to compare user's answer with program's condition, We have C-Language string library (i.e. string.h), include this before using any C-language inbuilt String function.
#include <string.h>
and use any of string function strcmp or stricmp as per requirement. Here I am going to use stricmp because it is possible that user may enter "no"/"No"/"NO". stricmp ignore the case.
stricmp(string1,string2)
It returns
Negative Number if string1 is less than string2
Zero if string1 equivalent to string2
Positive Number if string1 is greater than string2
So, for our case we check for Zero.
See the below program, I just added these in your code.
#include <stdio.h>
#include <string.h>
int main() {
int age, i;
char ans[5];//declare ans as character array
for (i = 0; i < 3; i++) {
printf("\n enter your age:");
scanf("%d", &age);
if (age > 18) {
printf("your age is %d, you are allowed to enter", age);
} else if (age == 18) {
printf("I don't know what to do with you");
} else {
printf("your age is %d, you are not allowed to go in", age);
}
printf("\n Do you want to continue(yes/no)?");
scanf("%s",ans);//take input as string in ans, its character array
if (stricmp(ans,"no") == 0) { // 0 means both are equal
break;
} else {
continue;
}
}
return 0;
}
You used %c which is for characters.
Instead, use %s.
I want to code a program which receives a number between zero and ten and shows a message saying it's valid or not. If not, it should keep asking for a valid number.
I could code everything and it seems pretty okay for me, but it's not working properly.
I have seen many topics with the similar problems, but I couldn't solve my problem. I mean, I had some progress, but my code isn't working yet.
What I did:
I created a variable to store the inserted value, used ctype library to make sure it will just accept numbers, converted my char to float and checked if it meets the requirements.
I tried some different codes, I googled it a lot and now I have no idea of what I should do.
CODE 1:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
main(){
char grade;
float grade2;
printf("Please, insert a grade between 0 and 10.\n");
printf("Grade: ");
scanf("%c",&grade);
while(isalpha(grade) || ispunct(grade) || isspace(grade) || iscntrl(grade)){
printf("Please, insert a valid value.\n");
fflush(stdin);
printf("Grade: ");
scanf("%c",&grade);
}
if(isdigit(grade)){
grade2 = atof(grade);
while(grade2 < 0 || grade2 > 10){
printf("\nPlease, insert a valid value.\n");
fflush(stdin);
printf("grade: ");
scanf("%c",&grade2);
}
printf("Valid value.\n");
}
else{
printf("Restart the program and try again.");
}
system("PAUSE");
}
The great problem with code 1 is that I get this:
[Error] invalid conversion from 'char' to 'const char*' [-fpermissive]
I just can't make it work, but it works here (code found on the internet):
#include <stdio.h>
#include <stdlib.h>
int main(){
char a[10] = "3.14";
float pi = atof(a);
printf("Value of pi = %f\n", pi);
return 0;
}
I thought it would be the scanf and initialization, but it worked receiving a value with scanf as well.
Finally, I thought it could be the array. I did:
CODE 2:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
main(){
char grade[50];
float grade2;
printf("Please, insert a grade between 0 and 10.\n");
printf("Grade: ");
scanf("%c",&grade[50]);
while(isalpha(grade[50]) || ispunct(grade[50]) || isspace(grade[50]) || iscntrl(grade[50])){
printf("Please, insert a valid value.\n");
fflush(stdin);
printf("Grade: ");
scanf("%c",&grade[50]);
}
if(isdigit(grade[50])){
grade2 = atof(grade);
while(grade2 < 0 || grade2 > 10){
printf("\nPlease, insert a valid value.\n");
fflush(stdin);
printf("Grade: ");
scanf("%c",&grade2);
}
printf("The grade is: %f\n", grade2);
printf("Valid value.\n");
}
else{
printf("Restart the program and try again.");
}
system("PAUSE");
}
It was always printing it's a valid value, no matter what number I wrote. So, I changed the code to see the value it was comparing and the output was:
Please, insert a grade between 0 and 10.
Grade: 11
The grade is: 0.000000
Valid value.
I googled it and I saw atof can return zero if something is wrong.
So, the last thing I tried to do was using this model: (also found on the internet)
double atof(const char *str)
Finally,
CODE 3:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
main(){
char grade;
printf("Please, insert a grade between 0 and 10.\n");
printf("Grade: ");
scanf("%c",&grade);
while(isalpha(grade) || ispunct(grade) || isspace(grade) || iscntrl(grade)){
printf("Please, insert a valid value.\n");
fflush(stdin);
printf("Grade: ");
scanf("%c",&grade);
}
if(isdigit(grade)){
float atof(grade *grade);
while(grade < 0 || grade > 10){
printf("\nPlease, insert a valid value.\n");
fflush(stdin);
printf("Grade: ");
scanf("%c",&grade);
}
printf("The grade is: %f\n", grade);
printf("Valid value.\n");
}
else{
printf("Restart the program and try again.");
}
system("PAUSE");
}
The output was:
Please, insert a grade between 0 and 10.
Grade: 11
Please, insert a valid value.
Grade: 6
Please, insert a valid value.
Grade: 10
Please, insert a valid value.
Grade: 5
Please, insert a valid value.
Grade:
I couldn't get out of the while.
I debugged it and found out it was stuck in the second while.
I tried to print the value again and I got another 0.000...
Well, I just came here because I did a good research on the internet but I still can't solve my problem.
I am sorry if I am doing anything wrong (like, violating a rule). If so, tell me and I will try to fix it.
Thank you for your attention.
Please try below code. It is self explanatory. If you need any specific explanation, please let me know.
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int isnumeric_array(char *string)
{
while( (char)(*string) != '\0') {
if( !isdigit( (char)(*string) ) ) {
return 0;
}
string++;
}
return 1;
}
int main(){
char grade[128];
float grade2;
read_input:
memset(grade, 0x0, sizeof(grade));
printf("Please, insert a grade between 0 and 10.\n");
printf("Grade: ");
scanf("%s", grade);
if(isnumeric_array(grade) == 0) {
goto read_input;
}
grade2 = atof(grade);
if((grade2 < 0) || (grade2 > 10)) {
goto read_input;
}
else {
printf("You have entered right value\n");
}
system("PAUSE");
}
fix your 2nd approach like this
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void){
char grade[50];
float grade2;//int grade2; ?
int invalid;//flag
int i;
printf("Please, insert a grade between 0 and 10.\n");
do {
invalid = 0;//false
printf("Grade: ");fflush(stdout);
fgets(grade, sizeof grade, stdin);
for(i = 0; grade[i] && grade[i] != '\n'; ++i){
if(!isdigit((unsigned char)grade[i])){
invalid = 1;//It contains illegal characters.
break;
}
}
if(!invalid){
grade2 = atof(grade);
if(grade2 < 0 || grade2 > 10){
printf("\nPlease, insert a valid value.\n");
invalid = 1;//Invalid input range
}
}
} while(invalid);
printf("The grade is: %f\n", grade2);
printf("Valid value.\n");
//printf("Restart the program and try again.");//never execute
system("PAUSE");
}
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.
I am writing a simple quiz in C (using CodeBlocks 13.12)
It compiles, but doesn't work in second question. Whatever I will input, it always give answer 'that's sad'.
I can't understand what is wrong.
I came to this, where if I comment line 13 ( scanf("%d", &age); ) it's starting works ok for second question.
What the problem is?
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <clocale>
int main()
{
int age;
char S1;
printf("How old is your dog? \n");
scanf("%d", &age);
if (age <= 7)
{
printf(" very young. the end \n");
return 0;
}
else
{
printf("old dog. \n \n");
}
//question2
printf("Do you like dogs? y/n \n");
scanf("%c%c", &S1);
if (S1 == 'y')
{
printf("hey, that's nice \n");
}
else
{
printf(" that's sad :( . \n");
return 0;
}
return 0;
}
You cause undefined behavior by
scanf("%c%c", &S1);
scanf reads two chars, one stored in S1, one stored in some location on the stack because scanf expects a second char* to be supplied.
If your intention is to ignore the newline following the actual character, write
scanf("%c%*c", &S1);
Change the second scanf() to
scanf(" %c", &S1);
This would escape the left out newline character \n in the input buffer.
Plus, you are reading one char in this. So you need only one %c
scanf("%c", &S1);
is the correct way to input one character ,
Below is a simple program that the user enters the number of subjects taken --> the grade (A,B,C etc.) --> and the program calculates and prints the students transcript including all the cgpa.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string[10];
char grade[10];
float out[10];
int num;
float cgpa=0.0;
for(int x=0;x<num;x++)
{
printf("\nEnter the number of subjects? \n ");
scanf("%d",&num);
printf("\nEnter Student Name: \n");
scanf("%s",&string[x]);
printf("\nEnter Student Grade: \n");
scanf("%s",&grade[x]);
if(grade[x]>="A" || grade[x]>="a")
out[x]==4.0;
else if(grade[x]>="B" || grade[x]>="b")
out[x]==3.0;
else if(grade[x]>="C" || grade[x]>="c")
out[x]==2.0;
else if(grade[x]>="D" || grade[x]>="d")
out[x]==1.3;
else if(grade[x]>="F" || grade[x]>="f")
out[x]==0.1;
else
printf("You've entered a wrong grade");
}
cgpa+=out;
cgpa=cgpa/num;
printf("%s\n", string);
printf("%s\n", grade);
printf("%f\n", cgpa);
getch();
}
My main problem is that I keep on getting the two following errors:
Cannot convert char to char*
illegal use of floating point
The errors I'm getting are on the following lines:
if(grade[x]>="A" || grade[x]>="a")
out[x]==4.0;
else if(grade[x]>="B" || grade[x]>="b")
out[x]==3.0;
else if(grade[x]>="C" || grade[x]>="c")
out[x]==2.0;
else if(grade[x]>="D" || grade[x]>="d")
out[x]==1.3;
else if(grade[x]>="F" || grade[x]>="f")
out[x]==0.1;
The illegal use of floating point error is on this line:
cgpa+=out;
Please see solution. Your original solution had a lot of issues and is fundamentally flawed. The above commentary highlight most of the mistakes you've made, but the main flaw with your original solution was the lack of clear process structure.
Recommend drafting out your algorithm or process flow before you begin coding in future
1. Grab user input for student name and number of subjects
2. For every subject
a. Get user to input grade
b. Check grade is valid
c. Add to cumulative GPA value
Until num_subjects is met
3. Print out Student Name, Num Subjects and his GPA (cgpa/num_subjects)
See sample solution below, which adheres to the process I defined above.
I hope this assists you in your programming journey :)
#include <stdio.h>
// #include <conio.h> - Commented this out because this is MS Dos specific and makes solution non portable
#include <ctype.h>
int main(void)
{
int num_subjects;
char name[10];
char grade;
float cgpa=0.0;
int x;
// These do not need to be within your loop. Especially num_subjects
printf("\nEnter Student Name: \n");
scanf("%s", &name[0]);
printf("\nEnter the number of subjects? \n ");
scanf("%d", &num_subjects);
// I've replaced this with a while loop, because you need a continuous loop until a valid grade is required
while( x < num_subjects )
{
printf("\nEnter Student Grade: \n");
scanf("%c", &grade);
// Upper case the value, so there is no ambiguity in 'a' or 'A'
grade = toupper(grade);
printf("\nGrade Entered: %c\n", grade);
if (grade == 'A') {
cgpa+=4.0;
}
else if (grade == 'B') {
cgpa+=3.0;
}
else if (grade == 'C') {
cgpa+=2.0;
}
else if (grade == 'D') {
cgpa+=1.3;
}
else if (grade == 'F') {
cgpa+=0.1;
}
else {
printf("You've entered a wrong grade");
// Being lazy here. I'm decrementing the counter, because I am lazy.
// By right, the efficient thing to do is to increment the counter on a valid value
// But in the interest of writing less code, I've decided to decrement the value on an invalid value.
// And add more comments :P
x--;
}
// Increment x if a valid grade was entered.
x++;
}
// Final output line
printf("\nStudent: %s, Number Subjects: %d, GPA: %.2f", name, num_subjects, cgpa/num_subjects);
}
You can't add a whole array to a floating point number.
And grade [x] is a char while "A" is a char array.
Also you have to scanf your number before using it in your for loop.
Change this:
if(grade[x]>="A" || grade[x]>="a")
out[x]==4.0;
For this:
if(grade[x]>='A' || grade[x]>='a')
out[x]=4.0;
Why?
reason 1: grade is an array of characters, not strings.
reason 2: == is a boolean operator (like the >= in your example). To set a variable value use just =
Study a little before coding. It is a very basic question.