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");
}
Related
# include<stdio.h>
int main() {
int marks;
printf("enter marks: ");
scanf("enter marks: %d ", &marks);
if(marks > 30)
{
printf("passed");
}
else
{
printf("not");
}
return 0;
}
The criteria that I put doesn't help in the output, even if enter marks as 14, then too it displays passed. I am a beginner, so please help.
printf("enter marks: ");
scanf("enter marks: %d ", &marks);
Is not correct.
You do not put a "prompt" in scanf. Only the value you want to read.
It should be:
scanf("%d", &marks); // Prompt was already done with printf on prior line
#include <stdio.h>
#include <conio.h>
int main() {
int marks;
printf("enter marks:");
scanf("%d",&marks);
if(marks > 30)
{
printf("passed");
}
else
{
printf("not");
}
return 0;
}
its working fine
So in this C code the program will give an error message that says "Invalid grade" and it asks the user to enter the grade again if the entered grade is >100 or <0, but this only happens once. If the user enters an invalid grade again the program returns black rather than giving the error message again and asking user to reenter the grade. How can I fix this?
#include <stdio.h>
#include <math.h>
int main()
{
double grade;
printf("Enter the student's grade: ");
scanf("%lf",&grade);
if (grade<0 || grade>100)
{
printf("Invalid grade\n");
printf("Enter the student's grade: ");
scanf("%lf", &grade);
}
if (grade>=90 && grade<=100)
printf("A");
if (grade>=80 && grade<=89)
printf("B");
if (grade>=70 && grade<=79)
printf("C");
if (grade>=60 && grade<=69)
printf("D");
if (grade<60 && grade>=0)
printf("F");
return 0;
}
This type of user-input validation code is where a do-while loop is idiomatic:
int scanned;
do
{
printf("Enter a grade between 0 and 100 (inclusive): ");
scanned = scanf(" %lf", &grade);
}
while(scanned != 1 && (grade < 0.0 || grade > 100.0));
Also note:
I check the return value of scanf to ensure that it's the same value as the number of format specifiers in the string. This tells me that scanf succeeded.
I put a space before the format specifier in the scanf format string. This consumes all whitespace left in the buffer prior to the new input.
You don't need to combine conditions with && operator.
if (grade >= 90)
{
printf("A");
}
else if (grade >= 80)
{
printf("B");
}
else if (grade >= 70)
{
printf("C");
}
else if (grade >= 60)
{
printf("D");
}
else if (grade >= 0)
{
printf("F");
}
Try this one:
#include <stdio.h>
#include <math.h>
int main()
{
double grade;
printf("Enter the student's grade: ");
scanf("%lf",&grade);
while (grade<0 || grade>100)
{
printf("Invalid grade\n");
printf("Enter the student's grade: ");
scanf("%lf", &grade);
}
if (grade>=90 && grade<=100)
printf("A");
if (grade>=80 && grade<=89)
printf("B");
if (grade>=70 && grade<=79)
printf("C");
if (grade>=60 && grade<=69)
printf("D");
if (grade<60 && grade>=0)
printf("F");
return 0;
}
This is hard to do with generality. scanf was not really meant for interactive programmes; see why not use scanf. The accepted answer of using a loop is good, and checking the return value is important. However, it fails for many edge cases; I've expended and covered some of them here as an addendum.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <math.h>
int main(void) {
int scanned, garbage, is_infected;
double grade;
const double max_grade = 100;
input:
printf("Enter a grade between 0 and %.0f (inclusive): ", max_grade);
/* Ignore leading whitespace. */
scanned = scanf(" %lf", &grade);
/* Ignore up to EOL for future input. */
is_infected = 0;
while((garbage = getchar()) != '\n' && garbage != EOF)
if(!isspace(garbage)) is_infected = 1;
if(is_infected) { fprintf(stderr, "Non-numerical input.\n"); goto input; }
/* `scanned` can be EOF, 0, or 1. */
switch(scanned) {
case EOF: /* EOF could mean different things. */
if(ferror(stdin)) { /* It could mean an error. */
/* ISO C doesn't strictly define whether bumped to `errno`. */
if(!errno) errno = EILSEQ;
perror("input");
} else { /* Or it could mean EOF. */
fprintf(stderr, "Premature EOF.\n");
}
return EXIT_FAILURE;
case 1: /* Successfully matched a double. */
/* `isnan` is C99; C90, `grade != grade` is true by IEEE754, which some
compilers relax. */
if(isnan(grade) || grade < 0.0 || grade > max_grade) {
fprintf(stderr, "Out of range [0, %.0f].\n", max_grade);
goto input;
}
grade = fabs(grade); /* For -0.0. */
break;
default: /* 0, unlikely (impossible?) because of clear of `stdin`. */
fprintf(stderr, "No number.\n");
goto input;
}
printf("number: %f\n", grade);
return 0;
}
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 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;
}
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.