I am new to programming and learning the C language and was practising structures and was trying to make basic school management system by using structures, but I am getting
too many errors (by using pointers in structures). So, can you please tell me what are the errors and how can I avoid these types of mistakes. Because, according to my understanding this should have been working.
Here is my code:
#include <stdio.h>
struct student {
int rollno;
char name[20];
float marks;
};
int main() {
again:;
while (1 == 1) {
struct student array[60];
char input;
int roll;
printf("What you would like to do:\n");
printf("Enter 'R' to fill the details again of all the student\n Enter 'U' to edit the
details of a single student\n");
printf("Enter 'S' to see the details of a particular student\n Enter 'A' to see the
details of every student\n");
scanf("%c", &input);
if (input == 'A' || 'a') {
for (int i = 0; i < 60; i++) {
printf("Roll no. : %d\n Name : %s\n Marks : %f\n", array[i].rollno, array[i].name,
array[i].marks);
}
}
else if (input == 'R' || 'r') {
for (int i = 0; i < 60; i++) {
printf("Roll no. os student is : %d\n", (i + 1));
printf("Enter students name :\n");
gets(array[i].name);
printf("Enter students marks :\n");
scanf("%f", &array[i].marks);
}
}
else if (input == 'S' || 's') {
printf("Enter the roll no. of the student of whom you want to see the details :\n");
scanf("%d", &roll);
printf("Roll no. :\n %d\n", roll);
printf("Name : \n");
puts(array[(roll - 1)].name);
printf("Marks : \n %f \n", (*(array + (roll - 1))->marks));
}
else if (input == 'U' || 'u') {
printf("Enter the roll no. of the student of whom you want to see the details :\n");
scanf("%d", &roll);
printf("Enter the name :\n");
gets((*(array + (roll - 1))->name));
printf("Enter the marks :\n");
scanf("%f", &(*(array + (roll + 1))->marks));
} else {
printf("Error Occured!!! \n");
printf("Re-enter your input\n");
goto again;
}
}
return 0;
}
There are many problems in your code:
there is no need for a goto again;, you already have an infinite loop while (1 == 1), which is usually written for (;;) in C. Don't use goto.
the definition struct student array[60]; should be moved outside the scope of the loop body. As posted, the array is discarded after each iteration and its contents become indeterminate.
array should be initialized to avoid undefined behavior when printing the contents before reading it from the user.
string literals cannot span multiple lines in a C source file. You can split them this way for readability:
printf("What you would like to do:\n"
"Enter 'R' to fill the details again of all the student\n"
"Enter 'U' to edit the details of a single student\n"
"Enter 'S' to see the details of a particular student\n"
"Enter 'A' to see the details of every student\n");
you should have a menu option to quit the program
reading a single character with scanf("%c", &input) is tricky: scanf() will read the pending newline from a previous call. You should use scanf(" %c", &input) where the space will cause pending whitespace to be read and discarded.
if (input == 'A' || 'a') does not test for A or a, it compares input to 'A' and if different compares 'a' to zero, hence the test is always true. You should write:
if (input == 'A' || input == 'a')
gets(array[i].name); is a NO NO. Don't use gets(), throw away the book that tells you to use it. For consistency with the other inputs, you can use
scanf("%19[^\n]", array[i].name);
Note that 19 tells scanf() the maximum number of characters to store into array[i].name before the null terminator, preventing undefined behavior for longer user input, and [^\n] causes scanf() to read and store characters up to and not including the newline character. %19s would stop at any white space, preventing the input of multiple words such as James Bond.
scanf("%f", &(*(array + (roll + 1))->marks)); is a very contorted way to write:
scanf("%f", &array[roll + 1].marks);
you should check the return value of scanf() to detect invalid input and flush the pending input on error.
Here is a modified version:
#include <stdio.h>
struct student {
int rollno;
char name[20];
float marks;
};
int main() {
struct student array[60] = { 0 };
int len = sizeof(array) / sizeof(*array);
int c, i, roll;
char input;
for (;;) {
printf("What you would like to do:\n"
"Enter 'R' to fill the details of all the student\n"
"Enter 'U' to edit the details of a single student\n"
"Enter 'S' to see the details of a particular student\n"
"Enter 'A' to see the details of every student\n"
"Enter 'Q' to quit the program\n");
if (scanf(" %c", &input) != 1)
break;
if (input == 'A' || input == 'a') {
for (i = 0; i < len; i++) {
printf("Roll no.: %d\nName: %s\nMarks: %f\n",
array[i].rollno, array[i].name, array[i].marks);
}
} else
if (input == 'R' || input == 'r') {
for (i = 0; i < len; i++) {
printf("Roll no. os student is: %d\n", i + 1);
printf("Enter student's name:\n");
if (scanf("%19[^\n]", array[i].name) != 1)
break;
printf("Enter students marks:\n");
if (scanf("%f", &array[i].marks) != 1)
break;
}
if (i < len) {
printf("Invalid input\n");
}
} else
if (input == 'S' || input == 's') {
printf("Enter the roll no. of the student of whom you want to see the details:\n");
if (scanf("%d", &roll) == 1 && roll >= 1 && roll <= len) {
printf("Roll no.: %d\nName: %s\nMarks: %f\n",
roll, array[roll - 1].name, array[roll - 1].marks);
} else {
printf("Invalid Roll no\n");
}
} else
if (input == 'U' || input == 'u') {
printf("Enter the roll no. of the student of whom you want to see the details:\n");
if (scanf("%d", &roll) == 1 && roll >= 1 && roll <= len) {
printf("Enter the name:\n");
scanf("%19[^\n]", array[roll - 1].name);
printf("Enter the marks:\n");
scanf("%f", &array[roll - 1].marks);
} else {
printf("Invalid Roll no\n");
}
} else
if (input == 'Q' || input == 'q') {
return 0;
} else {
printf("Invalid entry\n");
printf("Re-enter your input\n");
}
/* read and discard the rest of the input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
}
printf("Premature end of file\n");
return 0;
}
Related
I'm trying to create an array that allows me to enter the characters depending on the number that the user has previously entered, if I enter 10 I only want the user to enter 10 characters, A or F. The problem is that it does not work as expected, when entering the number it sends me to the while loop and does not let me exit.
#include <stdio.h>
int main() {
int i, students;
char grade[100];
printf("Welcome, enter the number of students to assign school grade: \n");
scanf("%d", &students);
printf("Enter A (Approved) or F (Failure)\n");
for (i = 0; i < students; i++) {
printf("School grade for student %d: \n", i + 1);
scanf("%c", &grade[i]);
while (grade[i] != 'A' || grade[i] != 'F') {
printf("Please enter a valid school grade: ");
scanf("%c", &grade[i]);
}
}
return 0;
}
After I enter the number 10, the program skips the second scanf and sends me into the while loop.
By changing scanf("%c", &grade[i]) into scanf (" %c", &grade[i]), the problem is that now the while loop is held even when I enter A or F.
Logic error. Your loop condition is always true.
while (grade[i] != 'A' || grade[i] != 'F')
If the value is A then it is not F. And vice versa.
It looks like you want:
while (grade[i] != 'A' && grade[i] != 'F')
This would loop while any value that is not A or F is entered. It's logically equivalent to:
while (!(grade[i] == 'A' || grade[i] == 'F'))
Please read De Morgan's laws for more information.
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;
}
Okay so I have run a function 4 times. It runs perfectly the first time but when i have to run that function again the 3 other time, i get the "* INVALID ENTRY * : " printf that i made when the user doesnt input a 'y' or 'Y' or 'n' or 'N'
Also, I am trying to make it so that whenever a user enters "Yes or No" it will prompt the "error message" but currently the way i wrote my program it takes only the first Character from the user" Ex: Inputs "Yes" the program will take only "Y" which makes the program think the user entered 'Y' which skips the error stage.
This is what is in my main
printf("Please enter 'Y' > ");
printf(" Result: %d\n", yes() );
printf("Please enter 'y' > ");
printf(" Result: %d\n", yes());
printf("Please enter 'N' > ");
printf(" Result: %d\n", yes());
printf("Please enter 'yes', then 'no', then 'n' > ");
printf(" Result: %d\n", yes());
And this is my part im trying to access.
int yes(void) {
char singleLetter;
int theResults = 0;
scanf("%c", &singleLetter);
while ((singleLetter != 'y') && (singleLetter != 'Y') && (singleLetter != 'n') && (singleLetter != 'N')) {
clearKeyboard();
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
scanf("%c", &singleLetter);
}
if ((singleLetter == 'y') || (singleLetter == 'Y')) {
theResults = theResults++;
}
if ((singleLetter == 'n') || (singleLetter == 'N')) {
theResults = 0;
}
//printf("%c",singleLetter);
return theResults;
}
The results are:
Please enter 'Y' > Y
Result: 1
Please enter 'y' > y
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: y
Result: 1
Please enter 'N' > N
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: N
Result: 0
Please enter 'yes', then 'no', then 'n' > yes
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: no
Result: 0
EDIT::
I fixed the above code so it works fine
However when I call yes() from a different function i get this error:
This is the code im trying to call from:
void getName(struct Name *contactName) {
printf("Please enter the contact's first name: ");
scanf("%s", (*contactName).firstName);
printf("Do you want to enter a middle intial(s)? (y or n): ");
yes();
if (yes() == 1) {
printf("Please enter the contact's middle intial(s): ");
scanf("%s", (*contactName).middleInitial);
}
printf("Please enter the contact's last name: ");
scanf("%s", (*contactName).lastName);
}
I fixed the yes() code with
int yes(void) {
char singleLetter;
int theResults = 0;
scanf("%c", &singleLetter);
clearKeyboard();
while ((singleLetter != 'y') && (singleLetter != 'Y') && (singleLetter != 'n') && (singleLetter != 'N')) {
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
scanf("%c", &singleLetter);
clearKeyboard();
}
if ((singleLetter == 'y') || (singleLetter == 'Y')) {
theResults = theResults + 1;
}
if ((singleLetter == 'n') || (singleLetter == 'N')) {
theResults = 0;
}
return theResults;
}
i get this error. Literally makes me enter y 3 times, and i get a invalid entry code for no reason.
Do you want to enter a middle intial(s)? (y or n): y
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: y
y
Please enter the contact's middle intial(s):
EDIT PART 2
I fixed my function yes() by doing this:
int yes(void) {
char singleLetter = ' ';
int finalValue = -1;
int theResult = 0;
scanf(" %c", &singleLetter);
clearKeyboard();
do
{
switch (singleLetter)
{
case 'Y':
case 'y':
finalValue = 1;
theResult = 1;
break;
case 'N':
case 'n':
finalValue = 0;
theResult = 1;
break;
default:
theResult = 0;
printf("Only (Y)es or (N)o are acceptable: ");
scanf("%c", &singleLetter);
clearKeyboard();
}
} while (!theResult);
return finalValue;
}
And this is the code im not sure with NEAR THE END OF THE CODE:
void getName(struct Name *contactName) {
printf("Please enter the contact's first name: ");
scanf("%s", (*contactName).firstName);
printf("Do you want to enter a middle intial(s)? (y or n): ");
if (yes() == 1) {
printf("Please enter the contact's middle intial(s): ");
scanf("%s", (*contactName).middleInitial);
}
printf("Please enter the contact's last name: ");
scanf("%s", (*contactName).lastName);
}
// getAddress:
void getAddress(struct Address *
contactAddress) {
printf("Please enter the contact's street number: ");
(*contactAddress).streetNumber == getInt();
printf("Please enter the contact's street name: ");
scanf(" %[^\n]", (*contactAddress).street);
printf("Do you want to enter an apartment number? (y or n): ");
if (yes() == 1) {
printf("Please enter the contact's apartment number: ");
scanf("%d", (*contactAddress).apartmentNumber);
}
printf("Please enter the contact's postal code: ");
scanf(" %[^\n]", (*contactAddress).postalCode);
printf("Please enter the contact's city: ");
scanf("%s", (*contactAddress).city);
}
// getNumbers:
// getNumbers:
// NOTE: Also modify this function so the cell number is
// mandatory (don't ask to enter the cell number)
void getNumbers(struct Numbers *contactNumber) {
printf("Please enter the contact's cell phone number: ");
scanf(" %s", (*contactNumber).cell);
printf("Do you want to enter a home phone number? (y or n) ");
if (yes() == 1) {
printf("Please enter the contact's home phone number: ");
scanf("%s", (*contactNumber).home);
}
printf("Do you want to enter a business number? (y or n) ");
if (yes() == 1) {
printf("Please enter the contact's business phone number: ");
scanf("%s", (*contactNumber).business);
}
printf("\n");
}
AND BELOW THAT I HAVE THIS AND DONT KNOW WHAT TO DO. AS I STATED IN THE COMMENT:
The purpose of this function is to set the values for a Contact using
the pointer parameter variable (set the Contact it points to).
Use the pointer parameter received to this function to supply the appropriate
Contact member to the “get” functions (getName, getAddress, and getNumbers) to set the values for the Contact.
void getContact(struct Contact *contact) {
getName(contact);
getAddress(contact);
getNumbers(contact);
}
THE BELLOW IS WHATS BEING ACCESSED/PRINTED. Whatever i enter, it doesnt show up because of void getContact(struct Contact *contact){ }
getContact(&contact);
printf("\nValues Entered:\n");
printf("Name: %s %s %s\n", contact.name.firstName, contact.name.middleInitial, contact.name.lastName);
printf("Address: %d|%s|%d|%s|%s\n", contact.address.streetNumber, contact.address.street,
contact.address.apartmentNumber, contact.address.postalCode, contact.address.city);
printf("Numbers: %s|%s|%s\n", contact.numbers.cell, contact.numbers.home, contact.numbers.business);
scanf retains the newline \n in the buffer, the next time scanf is executed, the newline is read instead. Consider this program:
#include <stdio.h>
int main(void)
{
char x;
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
return 0;
}
The output for the input w<ENTER>s<ENTER>
w
119: 'w'
10: '
'
In ASCII 119 is 'w' and 10 is '\n'.
If you add a getchar() after the scanf, then getchar() reads the newline
and then nothing is in the buffer left, then the next scanf waits for the user input again:
#include <stdio.h>
int main(void)
{
char x;
scanf("%c", &x);
getchar(); // <-- look here
printf("%d: '%c'\n", x, x);
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
return 0;
}
with the same input I get
w
119: 'w'
s
115: 's'
So, to solve your problem, you can add a getchar() after every scanf.
The best way to clear the buffer after using scanf:
int c;
while((c = getchar() !='\n') && c !=EOF );
EDIT
How to use fgets
man fgets
#include <stdio.h>
char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and stores them into the buffer
pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into
the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
Simply to get a line, you do:
char line[1024];
fgets(line, sizeof line, stdin);
fgets will returns NULL when there is no more lines to read or there is an
error. Either way when that happens, you usually stop reading the file. That's
why to read all lines from a file (or multiple lines from the user), you do
this:
char line[1024];
while(fgets(lines, sizeof line, stdin))
{
// do the work here
}
Bear in mind, that sizeof line in fgets is only correct, when line is an
array. If you for example allocate memory with malloc, you cannot use
sizeof line. If you get a pointer, then you have to know in advance how much
you can read.
size_t n = <some value>; // the value is not imporant,
// could be 100, could be 985
char *line = malloc(n);
if(line == NULL)
{
// error handling, for example return error value
}
// only if line is not NULL
fgets(line, n, stdin); // here I know the size in advance
// or as argument
void foo(char *buffer, size_t size)
{
fgets(buffer, size, stdin);
...
}
If the length of the line is lesser than the size (minus 1) of the buffer, the
newline character will be stored in the buffer. If you don't need it, you can
set it to 0 in order to get rid of the newline:
char line[1024];
fgets(line, sizeof line, stdin);
int len = strlen(line);
if(line[len - 1] == '\n')
line[len - 1] = 0;
But if you don't mind having the newline, then you don't have to do that.
So you could write your yes function with fgets. Get the whole line, even
if you are only interested in the first character, you can ignore the rest of
the characters in the line.
#include <ctype.h>
int yes(void) {
int theResults = 0;
char line[1024];
if(fgets(line, sizeof line, stdin) == NULL)
{
fprintf(stderr, "could not get line, aborting\n");
return -1; // error value
}
while(toupper(line[0]) != 'Y' && toupper(line[0]) != 'N') {
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
if(fgets(line, sizeof line, stdin) == NULL)
{
fprintf(stderr, "could not get line, aborting\n");
return -1; // error value
}
}
if(toupper(line[0]) == 'Y')
theResults++;
else
theResults = 0;
return theResults;
}
So basically after the calculation the program prompts the user if they want to quit the program and the user inputs a character ('y' or 'n') and if the user puts a number or letter that is not 'y' or 'n' then the program will keep prompting the user until they input one of the characters.
The issue I'm running into is that the program will keep looping and prompting the user even if 'y' or 'n' is inputted. When I try fflush(stdin) it still doesn't work
I want to know how to loop the statement again if the user does not input one of the options and when they do input it properly, how to get the code inside the "do while" loop to repeat. Preferably without having to copy and paste the whole bloc again.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");
scanf("%f", &x);
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
scanf("%f", &t);
}
fflush(stdin);
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
scanf() will not throw away the newline character '\n' in the input buffer unless your format string is set to discard it. In your code, after entering input for your floats and pressing Enter, the newline is still in the buffer. So for the code that prompts Y\N, use this format string to ignore the newline
scanf(" %c",&d);
You can remove the fflush() calls if you do that. In your case, it looks like your loop conditionals are wrong though.
This line
while (d != 'y' || d != 'n')
is wrong.
Think of it like this:
The loop runs if d is NOT 'y' OR d is NOT 'n'
Now imagine you put in 'y'
d is 'y'. The loop runs if d is NOT 'y' OR d is NOT 'n'. Is d != 'y'? No. Is d != 'n'? Yes. Therefore the loop must run.
You need to use &&
while (d != 'y' && d != 'n')
Also, scanf doesn't throw away the newline so add a space for all your scanfs.
scanf("%c", &d); //change to scanf(" %c", &d);
Look in this part-
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
you are using whiletwice, i think you will wish to have a single while condition over here.. also if you are terminating while, then be sure there is a doinvolved.
Here is code which I think is right since you have many problems so i just have changed a lot :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");//delete the repeat scanf
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
}
fflush(stdin);
sum=0;//no initalization
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while ((d != 'y' )&& (d != 'n'))//this logical expression is the right way
{
scanf("%c", &d);
fflush(stdin);
printf("\n****************************************");//I change the pos of print to avoid double printing
printf("\nDo you wish to quit? (y/n): ");
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
ps:for your calculate part of cos I'm not sure about the correctness while runing:)
I am trying to make a simple calculator in Turbo C(I have my own reasons to why I use Turbo C now)
#include <stdio.h>
#define P printf
int loop[] = {1, 1, 1, 1};
int num;
char input[64];
void main()
{
int num1, num2;
char x, y;
while(loop[0] == 1)
{
clrscr();
P("Hello!, This simple calculator will help you compute 2 numbers.");
P("\nPress the corresponding key to choose the operation you will use.");
P("\n\nA - (A)ddition");
P("\nS - (S)ubtraction");
P("\nM - (M)ultiplication");
P("\nD - (D)ivision");
P("\n\nAnswer: ");
while(loop[1] == 1)
{
x = getchar();
if(tolower(x) == 'a')
{
P("\nYou have chosen addition.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d + %d = %d", num1, num2, num1+num2);
}
else if(tolower(x) == 's')
{
P("\nYou have chosen subtraction.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d - %d = %d", num1, num2, num1-num2);
}
else if(tolower(x) == 'm')
{
P("\nYou have chosen multiplication.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d * %d = %d", num1, num2, num1*num2);
}
else if(tolower(x) == 'd')
{
P("\nYou have chosen division.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%g* %g = %.2f", (float)num1, (float)num2, (float)(num1/num2));
}
else
{
P("\nYou have entered an invalid character!");
P("\n\nAnswer: ");
continue;
}
while(loop[2] == 1)
{
P("\n\nDo you want to do another calculation? Y/N: ");
y = getchar();
if(tolower(y) == 'y' || tolower(y) == 'n')
{
loop[2] = 0;
}
else
{
P("\nYou have entered an invalid character.");
continue;
}
}
loop[1] = 0;
}
if(tolower(y) == 'y')
{
continue;
}
if(tolower(y) == 'n')
{
loop[0] = 0;
}
}
}
int askForNumber(const char *string)
{
P("%s", string);
while(loop[3] == 1)
{
fgets(input, (sizeof(input)/sizeof(input[0]))-1, stdin);
if(sscanf(input, "%d", &num) != 1)
{
num = 0;
P("Invalid number!");
continue;
}
return num;
}
}
I have these bugs:
After I finish a calculation, and press 'Y', it clears the screen non-stop.
After "Enter 1st number: ", the "Invalid number" shows up once even though I haven't typed anything yet(but i can still input a number and it will be saved to 'num1', "Invalid number just bugs me".
At the top where I am to input 'a' or 's' or 'm' or 'd' to choose an operation, if I put some letter except for that above, i get this
OUTPUT:
Answer: o
You have entered an invalid character!
Answer:
You have entered an invalid character!
Answer:
the error shows up twice, but i only typed once.
When there are no characters in the input buffer, the getchar function blocks until the return key is pressed. All keys, including return, are stored in the input buffer, then getchar returns the first character in the buffer. The next call to getchar will immediately return the next character in the buffer.
So if you press 'y' then return, the first call to getchar returns the 'y' character, and the next returns a newline character, i.e. the return key.
You need to flush the input buffer each time you use getchar to skip over the newline:
do {
c = getchar();
} while (c == '\n');
You nedd #include ctype.h to lower is part of that library tolower uses this library and its nowhere in your code