scanning an array and assign it into other place in C - c

help me. I've been assign to make an application for some test result. but why can't I print out what user have inputted at case 2. I've tried other approach but it's not working. this is the closest I could get there. Any help would be appreciated. super thanks +_+
this is my code :
int main(){
int option;
char namamurid[30][15];
int i=0,j=0;
int listening[15];
int reading[15];
int essay[15];
int score[15];
do{ printf("\"Smart English\" Course Center\n********************************\n");
printf("1.Add new data\n2.View data\n3.View summary\n4.Exit\n\n");
printf("your option[1..4]: ");
scanf("%d",&option);
fflush(stdin);
switch(option){
case 1:
do{
printf("Input student's name[1..25 char]: ");
scanf("%[^\n]s",namamurid[i]);
fflush(stdin);
}while(strlen(namamurid[i])<1 || strlen(namamurid[i])>25);
do{
printf("Correct answer for listening section[0..20]: ");
scanf("%d",&listening[i]);
fflush(stdin);
}while(listening[i]<0 || listening[i]>20);
do{
printf("Correct answer for reading section[0..30]: ");
scanf("%d",&reading[i]);
fflush(stdin);
}while(reading[i]<0 || reading[i]>30);
do{
printf("Correct answer for essay section[0..25]: ");
scanf("%d",&essay[i]);
fflush(stdin);
}while(essay[i]<0 || essay[i]>25);
break;
case 2:
printf("Name\t\tListening\tReading\tEssay\tScore\tGrade\n");
for(j=0;j<i;j++)
{
printf("%-1s\t\t%d\t%d\t%d\t%d\n",namamurid[j],listening[j],reading[j],essay[j],score[j]);
}
break;
}
} while(option<1 || option>4 || option !=4);
getchar();
return 0;
}

There is no change to value of variable i which is set to 0 during initialization.Hence it will never enter the for loop in case 2.

Related

C - 2 or more input validation inside while loop

I have a program in which it will ask for the user to record the student's name and grade. One of the functions I used is for the user to edit the record of the student. The code works but now what I'm scratching my head is how to implement a validation of input by the user. I tried searching but I can't find the exact answer I need.
I already implemented the first validation and it works, but now what I want for the second validation is to go back and ask again instead of breaking the loop.
Here's my code:
void update(struct data list[80], int num)
{
int count, tmp, rolltmp, option;
system("cls");
while(tmp < 1 || tmp > num)
{
printf("How many student records do you want to edit?: ");
scanf("%d",&tmp);
if(tmp >=1 && tmp <=num)
{
printf("\nEditing the Student Record: ");
for(count=0;count<tmp;count++)
{
printf("\nEnter Roll Number for Student #%d: ",count+1);
scanf("%d",&rolltmp);
if(rolltmp >=1 && rolltmp <= num)
{
fflush(stdin);
printf("\n[CHOICES]");
printf("\n[1] - Edit the Name\n[2] - Edit the Grade\n[3] - Edit Both Name and Grade");
printf("\nEnter Choice: ");
scanf("%d",&option);
switch(option)
{
case 1:
fflush(stdin);
printf("\nEnter New Name: ");
gets(list[rolltmp-1].name);
break;
case 2:
printf("\nEnter New Grade: ");
scanf("%d",&list[rolltmp-1].grades);
break;
case 3:
fflush(stdin);
printf("\nEnter New Name: ");
gets(list[rolltmp-1].name);
fflush(stdin);
printf("\nEnter New Grade: ");
scanf("%d",&list[rolltmp-1].grades);
break;
}
}
else
{
printf("\nNot Valid. Please enter from 1 to %d\n",num);
printf("Press any key to enter again...\n\n");
getch();
break;
}
}
}
else
{
printf("Not Valid. Please enter from 1 to %d",num);
getch();
break;
}
}
}

if statement with char condition in C

I have been working on a college project. I want user to enter Y/N if he wants to continue or not, so I wrote following code
repeat:
pr=0;
q=0;
res=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
billing(pr,q);
printf("Continue Shopping? (y/n) ");
scanf("%d",&res);
if(res=='y')
goto repeat;
else
return 0;
}
The problem is entering y executes else statement. I tried replacing y with 1,2,3.... and it works but I want it to work with Y or y or yes.
There is a bug in this line
scanf("%d",&res);
It should be
scanf(" %c",&res);
The formatting placeholders for char is %c not %d
scanf("%d",&res);
should be
scanf(" %c",&res);
As suggested by multiple users do while should be used over goto, so better code would be
do{
pr=0;
q=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
billing(pr,q);
printf("Continue Shopping? (y/n) ");
scanf(" %c",&res);
}
while(*res == 'Y' || *res == 'y');
return 0;
}
Also res should also be declared char res;

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.

How to make a function in 'C' to go to start of program

I am a beginner in C...
I have made a made a calculator type program which uses four basic functions in C using if-else loop.
I want when the program comes to end(after the user has added, subtracted etc. etc. then there is a option "Y/N" so that the program can be restarted???"
Here is the sample of the code
#include<stdio.h>
int main()
{
int choi;
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==4)
{
float a=0,b=0,c=0;
printf("\nEnter Divident :");
scanf("%d",&a);
printf("\nEnter the Divisor :");
scanf("%d", &b);
c=a/b;
printf("\nThe Quotient is : %d\n\n",c);
char choice;
printf("Do you want to try it again?(Y/N) ");
scanf("%c", &choice);
// I want a code here so that the program can be restarted
getch();
return 0;
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2 or 3 !\n\n");
}
end:
getch();
return 0;
}
The best way would be to do some sort of a while loop.
int goAgain=1;
while (goAgain==1) {
... //Normal code here
printf("Again?")
scanf("%c",&again)
if (again=='N') {
goAgain=0;
}
}
Or you could use a do-while loop as well
do {
... //Normal code here
printf("Again?")
scanf("%c",&again)
} while (again=='Y')
Basically, this will keep looping over the bit of code over and over until the person types N to end it.
A do-while loop would be most suitable for this purpose.
int main() {
char choice;
do {
// Calculator stuff here...
printf("Do you want to try it again? (Y/N) ");
scanf("%c", &choice);
} while (choice == 'Y');
}
Edit: As it turns out, there is another problem with the program above, which is that scanf() reads a character but leaves a Newline character in the buffer. Therefore, if the user types YEnter, the program will repeat once (choice == 'Y' the first time), then exit (choice == '\n' the second time).
It is therefore necessary to keep reading until the Newline has been consumed.
int main() {
char choice;
do {
// Calculator stuff here...
printf("Do you want to try it again? (Y/N) ");
choice = getchar();
while (choice != '\n' && getchar() != '\n') {};
} while (choice == 'Y' || choice == 'y');
}
char continue = 'Y'
while (continue == 'Y') {
... //Normal code here
printf("Again?")
scanf("%c",&continue)
}
you can try like this, avoid go to
#include<stdio.h>
int main()
{
int choi;
while(true)
{
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\n5. Exit");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==1)
{
}
else if(choi==2)
{
}
else if(choi==3)
{
}
else if(choi==4)
{
}
else if(choi==5)
{
return 0; //exit(0);
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2,3,4 or 5 !\n\n");
}
}
return 0;
}
By using do-while loop, which is generally used for menu-driven programs.
#include<stdio.h>
int main()
{
int choi;
char choice;
do{
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==4)
{
float a=0,b=0,c=0;
printf("\nEnter Divident :");
scanf("%d",&a);
printf("\nEnter the Divisor :");
scanf("%d", &b);
c=a/b;
printf("\nThe Quotient is : %d\n\n",c);
char choice;
printf("Do you want to try it again?(Y/N) ");
scanf("%c", &choice);
// I want a code here so that the program can be restarted
getch();
return 0;
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2 or 3 !\n\n");
}
printf("Want to continue (y/n)?");
scanf("%d", &choice); // Enter the character
}while (choice == 'y' || choice == 'Y');
end:
getch();
return 0;
P.S.: I would suggest you to use switch case, instead of if-else statements to do the job.
You can also use a goto:
int main() {
...
if (c=='y') {
main();
} else {
goto end;
}
end:
...
}

scanf is skipped even if using fflush

I have a scanf that doesn't accept input. The value is automatically zero, even if the variable wasn't initialized. The scanf is skipped:
printf("\nEnter the number of the student to be dropped: ");
fflush(stdin);
scanf(" %d ",&choice);
printf("choice is %d", choice);
When the program is run, it immediately displays "choice is 0".
The snippet above is taken from the drop() function in this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student{
char name[50];
char* course;
};
main()
{
char repeat;
do{
system("cls");
int mainchoice;
printf("Student Enrollment System");
printf("\n");
printf("\n");
printf("1. View\n");
printf("2. Enroll\n");
printf("3. Drop enrollment\n");
printf("Select choice: ");
fflush(stdin);
scanf("%d",&mainchoice);
system("cls");
switch(mainchoice){
case 1:
view();
break;
case 2:
enroll();
break;
case 3:
drop();
break;
default:
printf("Please enter a valid number.");
getch();
fflush(stdin);
break;
}
printf("\nWould you like to make another transaction? [Y/N]: ");
fflush(stdin);
scanf("%c",&repeat);
}while(repeat=='Y'||repeat=='y');
}
view(){
int ctr = count();
printf("Enrolled Students:\n\n");
system("type records.txt");
printf("\n\nNumber of students enrolled: %d", ctr);
getch();
fflush(stdin);
}
enroll(){
int choice;
char validate;
printf("1. Information Technology\n");
printf("2. Computer Science\n");
printf("3. Computer Engineering\n");
printf("4. Information Systems\n");
struct student news;
printf("Name: ");
fflush(stdin);
gets(news.name);
printf("Course Number: ");
fflush(stdin);
scanf("%d", &choice);
switch(choice){
case 1:
news.course = "BSIT";
break;
case 2:
news.course= "BSCS";
break;
case 3:
news.course = "BSCpE";
break;
case 4:
news.course = "BSIS";
break;
default:
printf("Please enter a valid number\n");
break;
}
printf("Enroll %s to %s? [Y/N]:",news.name,news.course);
fflush(stdin);
scanf("%c", &choice);
if(choice=='Y' || choice=='y')
{
FILE * records;
records = fopen("records.txt", "a+");
fprintf(records, "%s, %s\n",news.name,news.course);
fclose(records);
printf("%s has been enrolled to %s\n",news.name, news.course);
}
else
{
printf("You have chosen to cancel your transaction");
}
}
drop(){
printf("Drop Student:\n\n");
int ctr = 0;
int choice; //which student to delete
char c;
FILE * record; // original records.txt
FILE* repo; //temporary data storage
record = freopen("records.txt", "r", stdin);
while((c = fgetchar())!=EOF){
if(c == '\n'){
}
else{
ctr=ctr+1;
printf("%d. ", ctr);
while(1){
printf("%c",c);
c= fgetchar();
if(c=='\n'){
printf("%c",c);
break;
}
}
}
}
fclose(record);
fflush(stdin);
fflush(stdin);
printf("\nEnter the number of the student to be dropped: ");
fflush(stdin);
scanf(" %d ",&choice);
getch();
getch();
fflush(stdin);
ctr = 1;
fflush(stdin);
repo = fopen("temp.txt","w");
record = freopen("records.txt","r",stdin);
while((c = getchar()) != EOF){
if(c == '\n'){
}
else{
while(ctr!=choice){
fprintf(repo,"%c",c);
c= fgetchar();
if(c=='\n'){
fprintf(repo,"%c",c);
ctr = ctr + 1;
break;
}
}
}
}
fclose(record);
fclose(repo);
getch();
}
//counts the number of rows in the record
int count(){
int ctr=0;
char c;
FILE * records;
records = freopen("records.txt","r", stdin);
if(records!=NULL){
while((c=fgetchar()) !=EOF){
if(c=='\n'){
ctr = ctr+1;
}
}
}
fclose(records);
return ctr;
}
Doing fflush doesn't seem to help. Any ideas?
The behavior of fflush is not defined for input streams; fflush(stdin) is a coding error, and you should remove those calls from your code.
When scanning for individual characters, add a blank space before the %c conversion specifier; this will tell scanf to skip any leading whitespace and read the next non-whitespace character:
scanf(" %c", &choice);
The %d and %s conversion specifiers will skip over any leading whitespace.
Edit
Implicit typing is no longer supported as of C99, and it's a bad habit to get into. Explicitly type your functions, and use void as the parameter list to specify that they take no arguments:
main() => int main(void)
view() => void view(void) // void since it isn't returning a value
drop() => void drop(void)
etc.
Similarly, gets was deprecated in C99 and is gone completely as of the 2011 standard. Using it will introduce a point of failure / major security hole in your program. Use fgets instead.

Resources