Here's a part of a function that supposed to scan an integer between 0 and 100.
The program goes wrong when the user inputs a char. anyone has an idea? iv'e tried a Combined condition like this one: if(scanf("%d",&test)&&(test<=100&&test>=0))
it didn't work...
while(i!=4)
{
printf("\nPlease enter your homework grade: ");
if(scanf("%d",&hw))
{
++i;
}
if(hw<=100&&hw>=0)
{
++i;
}
printf("\nPlease enter your test grade: ");
if(scanf("%d",&test))
{
++i;
}
if(test<=100&&test>=0)
{
++i;
}
else
{
printf("\nPlease re-enter the required details\n");
i=0;
}
}
When a character is read using %d then the ASCII value of it is stored in the memory.
If you want a Integer Proofing mechanism, then use the below code. Get the user input as a string, check if any character is present, if present then return error, else convert that string to integer and use the same for further processing.
char n[4]; /* To store max of 3 char's `100` including '\0' */
int i=0, flag=1;
scanf("%3s", n);
while(n[i] != '\0'){
flag = isdigit(n[i]);
if (!flag)
break;
i++;
}
if(flag)
{
i=atoi(n);
printf("%d", i);
}
else
{
printf("it's not integer");
}
you have to make while(i!=2){....}
Try the program in this way....
main()
{
int i, hw, test;
while(i!=2)
{
i=0;
printf("\nEnter the hmwrk grade: ");
if(scanf("%d",&hw)&&(hw<=100&&hw>=0))
++i;
printf("\nEnter the test grade: ");
if(scanf("%d",&test)&&(test<=100&&test>=0))
++i;
if(i!=2)
printf("\nPlease reenter the req details..\n");
}
}
Related
I need the code below to recognize if the grades entered is below 1 or greater than 100. If it is not within the parameters, I want to let the user know and allow them to enter another grade without exiting the program or losing grades they have already entered. I don't want the program to quit until the user enters q and I want to ensure all of the valid grades entered print at that time. I have tried numerous methods and am not getting the right results. I think I probably need some other else if statement, but I haven't been able to find the right one to work. Any information you can share to get me on the right track would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
You can do a while loop to verify the user input. With a while you'll be able to force the user to enter the right grade.
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
your solution is almost aligned with what you had in mind. Here is how you can do it differently.
#include <stdio.h>
int main()
{
char choice;
int arraySize = 100; //change this to any number you wish
int gradeScore = 0;
int gradeArray[arraySize];
int gCount = 0;
int showCount = 0;
while(choice != 'q')
{
//to ask for user's input every time
printf("What do you want to do? Enter\n");
printf("'a' to add grades\n");
printf("'q' to quit\n");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
//your implementation should check for user input before proceeding
if(choice != 'a')
{
//in this condition, 'q' is technically an incorrect input but your design states that 'q' is for quitting
//thus, do not alert the user here if 'q' is entered
if(choice != 'q')
{
//a condition to warn the user for incorrect input
printf("Incorrect input. Please enter only 'a' or 'q'\n");
}
}
else if(choice == 'a')
{
printf("Enter grade: \n");
scanf(" %d", &gradeScore);
//to check for user input if the grades entered are less than 1 or more than 100
if(gradeScore < 1 || gradeScore >100)
{
//print a warning message
printf("The grade you entered is invalid. Please enter a grade from 1 - 100\n");
}
//for all correct inputs, store them in an array
else
{
printf("Grade entered\n");
gradeArray[gCount] = gradeScore;
gCount++;
}
}
}
//prints grade when 'q' is entered
if(choice == 'q')
{
printf("Grades are: \n");
for(showCount = 0; showCount < gCount ; showCount++)
{
printf("%d\n", gradeArray[showCount]);
}
}
}
To sum up the important parts, be sure to check for the user grade input to be in range of 1 - 100. Store the grade in the array if it is within range and be sure to increase the array counter, otherwise it will always store it in gradeArray[0] for the subsequent grades. Hope this helps
Use a do-while loop to keep the program looping back to get another choice unless a valid choice has been entered. Use fgetc to read a single character - fewer problems. Only print grades if at least one grade has been entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection******\n Add grades(a)\n Quit(q) \n");
do
{
choice = fgetc(stdin);
if(choice == 'a' || choice == 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
else if(choice != 'q')
printf("Invalid choice - try again\n");
} while (choice != 'a' && choice != 'A' && choice != 'q');
if(choice == 'q') //if the user choice is q, then exit the loop
break;
}
if(gCount > 0)
{
printf("Grades are:\n");
for(i=0; i<gCount; i++)
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
I'm creating a program that asks for input and then based on the input rejects it or accepts it. This is the code:
while(1){
printf("Enter name: ");
scanf("%s", &name);
if(name[0] == '\0'){
printf("Input Cannot be empty\nExample: bobshmurda\n");
} else {
break;
}
}
printf("Enter age: ");
scanf("%d", &age);
while(!age>= 15){
printf("Age\n");
}
while(1){
printf("Enter MMN: ");
scanf("%d", &mmn);
if (!cvv >= 3){
printf("\nInvalid MMN... Try again\n");
} else {
break;
}
}
while(1){
printf("DOB: ");
scanf("%d", &dob);
if (!exp == 4){
printf("Invalid DOB detected... Format: 0123\n");
} else {
break;
}
}
What i basically want to do is i want to for example IF age is greater than 100 or less than 0 do this, etc. Same with strings how would i do that?
A do-while loop is probably the simplest method:
int is_valid = 0;
do {
// Get user input here
is_valid = validate_input(...);
} while (! is_valid);
// Continue with processing...
How do I make my if statement ask the user to try again if the input is a negative number or a letter?
struct foodstuff {
float amount;
};
void add(struct foodstuff *tmpAdd) {
printf("Write amount: ");
scanf("%f", &tmpAdd->amount);
while (tmpAdd->amount != 0) {
if (tmpAdd->amount < -1 || isalpha(tmpAdd->amount)) {
printf("Type in a valid number!\n");
printf("Write amount: ");
getchar();
scanf("%f", &tmpAdd->amount);
getchar();
}
else {
scanf("%f", &tmpAdd->amount);
getchar();
}
}
};
I think you can rephrase your code to use a do loop instead:
do {
printf("Enter a positive number with no characters:\n");
int result = scanf("%f", &tmpAdd->amount);
while (tmpAdd->amount <= 0 || result != 1);
Note that I have removed the call to isalpha(), which acts only a single character at a time. Instead, I propose just checking that the entered number is a valid float and that it is greater than zero. If scanf does not succeed to read in a valid float, then its return value would be not be 1 and the loop would repeat. And the same is the case for entering a valid float which is a negative number.
As chux said, you could first read the input with fgets() and then parse it.
Like
char buff[100], *ptr;
float f;
while(fgets(buff, sizeof(buff), stdin)!=NULL)
{
buff[strlen(buff)-1]='\0';
f=strtof(buff, &ptr);
if(errno==ERANGE)
{
printf("\nPossible overflow.");
errno=0;
continue;
}
if(f<0 || *ptr!='\0')
{
printf("Type in a valid number!\n");
continue;
}
tmpAdd->amount=f;
printf("\n%f", f);
}
Here, fgets() is used to read the input on each iteration. fgets() will return NULL upon error.
The
buff[strlen(buff)-1]='\0';
is done because fgets() will read in the trailing \n into buff as well. We modify that \n to be the \0 character denoting the end of string with buff[strlen(buff)-1]='\0';.
strtof() is used to extract the value from buff.
It is in stdlib.h.
In case buff has something other than numbers, the number part would be converted and returned by strtof() and the ptr pointer would be made to point to the first non-numeric part of buff.
So if the first character in the string pointed to by ptr is the \0 character, there were no non-numeric parts in buff.
If the input value was too large or too small to be accommodated in a float, errno would be set to ERANGE. You need to include errno.h for that.
If overflow (or underflow) occurred, we set errno to 0 and continue.
And (tmpAdd->amount<-1) would be false even if tmpAdd->amount were -1 and -1 is negative. You need (tmpAdd->amount<0) instead.
Also, your loop would exit only when tmpAdd->amount becomes 0. You could simply do
tmpAdd->amount=0;
if that would do.
Otherwise, you can add a
if(f==0)
{
break;
}
at the end of the while loop.
I did some changes to my code, it looks like this now:
printf("Write amount: ");
scanf("%f", &(tmpAdd + index)->amount);
getchar();
do {
if (tmpAdd->amount <= -1 || isalpha(tmpAdd->amount != 0)) {
printf("Type in a valid number!\n");
printf("Write amount: ");
scanf("%f", &(tmpAdd + index)->amount);
getchar();
}
else if (isdigit(tmpAdd->amount >= 0)) {
scanf("%f", &(tmpAdd + index)->amount);
//getchar();
}
} while (tmpAdd->amount <= -1 || isalpha(tmpAdd->amount != 0));
};
Main looks like this:
int main (void) {
int input, noFood = 0;
int flag = 1;
printf("Welcome to the shopping list manager. \n\n");
struct foodstuff food1;
while (flag == 1) {
printf("1 - add food\n");
printf("2 - print shopping list\n");
printf("3 - end\n\n");
printf("What do you want to do? ");
scanf("%d", &input);
clear();
switch (input) {
case 1: add(&food1, noFood); noFood++; break;
case 2: print(&food1, noFood); break;
case 3: printf("\nExiting program\n"); flag = 0; break;
default: printf("Please enter a valid choice\n");
}
}
return 0;
}
And the output like this:
Output
The only problem remaining is that when I want to add another item (add food) for the second time and I type a letter or a negative number, it doesn't run through the if statements.
I have a problem with a program that should split a phone number(ex. 1231231234) that user enters into three groups and display them like this (123)-123-1234. I'm not sure how to split this number and what to use in order to complete it. I didn't completed the code party but here's what i got.
#define SIZE 3
int main(void){
int option, j;
int phList = 0;
int phoneNum[SIZE];
printf("---=== Phone Numbers ===---\n");
while(1){
printf("\n");
printf("1. Display Phone List\n");
printf("2. Add a Number\n");
printf("0. Exit\n");
printf("\n");
printf("Please select from the above options: ");
scanf("%d", &option);
if(option == 0){
printf("Exiting Phone Number App. Good Bye!!!\n");
return 0;
}
if(option == 1){
printf("\n");
printf("Phone Numbers\n");
printf("==============\n");
for(j = 0; j < phList; j++){
printf("\n", phoneNum[j]);
}
}
if(option == 2){
if(phList < SIZE){
printf("\n");
printf("Add a Number\n");
printf("============\n");
scanf("%d", &phoneNum[phList]);
phList++;
} else {
printf("Add a Number\n");
printf("============\n");
printf("ERROR!!! Phone Number List is F$
}
}
}
return 0;
}
I would consider using fgets() to get the phone number as a string, rather than getting it as an integer. Then you can filter the input so that only the digits are kept, allowing users to enter parenthesis, spaces, or dashes as desired. Finally, sscanf() can be used to scan the filtered string into three strings for the area code, exchange number, and subscriber number. If you like, these strings can be converted to numbers by atoi() or strtol().
The OP seems to be assuming that the phone number follows the format of the North American Numbering Plan, but phone number formats may differ. The string representation is more flexible than an integer representation, making future modifications to the code easier.
Here is an example of how this might be done:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void filter_num(char *str);
int main(void)
{
char buffer[1000];
char area_code[4];
char xch_num[4];
char sub_num[5];
printf("Enter phone number: ");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
fprintf(stderr, "Error in fgets\n");
exit(EXIT_FAILURE);
}
filter_num(buffer);
if (sscanf(buffer, "%3s%3s%4s", area_code, xch_num, sub_num) != 3) {
fprintf(stderr, "Phone number format error\n");
exit(EXIT_FAILURE);
}
printf("Phone number is: (%s) %s-%s\n",
area_code, xch_num, sub_num);
return 0;
}
void filter_num(char *str)
{
char *p = str;
while (*p != '\0') {
if (isdigit(*p)) {
*str++ = *p;
}
++p;
}
*str = '\0';
}
I will suggest defining a function to split the number and display that, Please have a look on this one, I have written it for you just now and works fine:
void DisplayNum(long long int PhNum)
{
printf("\n ");
for(int i=1; i<=10; ++i) // Since Phone Number Contains 10 digits
{
int digit= PhNum/(pow(10,10-i)); // Spliting digits
digit= digit%10;
if(i==1)
{
printf(" (");
}
if(i==4)
{
printf(")-");
}
if(i==7)
{
printf("-");
}
printf("%d",digit); // Displaying Digits
}
}
But make sure to use #include<math.h> at the beginning because i am using pow() function here. Then you can just pass each Phone Number in array to display to this function. The for-loop to display each Phone Number in array will be like :
for(j = 0; j < phList; j++){
DisplayNum(phoneNum[j]);
}
I am working on a program in C that can return loan payment.
yearInt is year interest
loanAmt is total amount of loan
monthlyPay is monthly payment
numberPay is number of monthly payment
For some reasons, when I run the program, there is nothing shows up, even I type in a negative number.
Is there anyway to fix it?
#include <stdio.h>
int main(void)
{
float yearInt = -1;
int loanAmt = -1;
float monthlyPay = -1;
int numberPay = -1;
int count = 0;
while (loanAmt<0)
{
printf("Please enter valid loan value: \n");
scanf("%f", &loanAmt);
}
while (yearInt<0)
{
printf("Please enter valid yearly interest value: \n");
scanf("%f", &yearInt)
}
while (monthlyPay<0)
{
printf("Please enter valid monthly payment value: \n");
scanf("%f", &monthlyPay);
}
while (numberPay<0)
{
printf("Please enter valid number of monthly payments: \n");
scanf("%f", &numberPay);
}
if(loanAmt>monthlyPay)
{
while(count<numberPay)
{
loanAmt = loanAmt*(1 + (yearInt/12)) - monthlyPay;
count += count+1;
}
printf("The amount of last payment is: %.2f\n", loanAmt);
else
printf("The amount of last payment is: %.2f\n", loanAmt);
}
return 0;
}
You are using the wrong format specifier to read loanAmount and numberPay. Instead of "%f", use "%d".
scanf("%d", &loanAmt);
and
scanf("%d", &numberPay);
Also, always check the return value of scanf to make sure that it was able to assign data to all the variables.
Change the loop:
while (loanAmt<0)
{
printf("Please enter valid loan value: \n");
scanf("%d", &loanAmt);
}
to
while (loanAmt<0)
{
printf("Please enter valid loan value: \n");
if ( scanf("%d", &loanAmt) != 1 )
{
// Discard the rest of the line.
int c;
while ( (c = fgetc(stdin)) = '\n' && c != EOF );
}
}
It will be still better to put all the checks in a function and call the function from main.
int readInt(char const* prompt)
{
int val = -1;
printf("%s\n", prompt);
while ( scanf("%f", &val) != 1 || val < 0)
{
// Discard rest of the line.
int c;
while ( (c = fgetc(stdin)) = '\n' && c != EOF );
// If EOF is reached, we have a problem.
if ( c == EOF )
{
exit(0);
}
printf("%s\n", prompt);
}
return val;
}
and then, use:
loanAmount = readInt("Please enter valid loan value: ");
Add a similar function to read floats and call it for reading the variables that are of type float.
scanf("%f", &loanAmt); // loanAmt is int
...
scanf("%f", &numberPay); //numberPay is int
In both wrong argument is passed to %f , therefore , causes UB . Use %d specifier .
And in this one } is missing -
if(loanAmt>monthlyPay)
{
while(count<numberPay)
{
loanAmt = loanAmt*(1 + (yearInt/12)) - monthlyPay;
count += count+1;
}
printf("The amount of last payment is: %.2f\n", loanAmt); //use %d
// ADD '}' here
else // ADD '{' here
printf("The amount of last payment is: %.2f\n", loanAmt); //use %d
}
Put a } before else {.