?? tovote.c
字號(hào):
/* candidatenum.c :給候選人投票 */
#include "stdio.h"
void Vote()
{
int i,j,k;
long candidatenum; /*存儲(chǔ)用戶輸入的要投票的候選人序號(hào)*/
/*輸入各項(xiàng)修改后信息*/
long Number;
candidate TmpS; /*定義進(jìn)行操作時(shí)的臨時(shí)結(jié)構(gòu)體變量*/
candidate s[10];/*10個(gè)候選人 */
int recNumber;
char DataFile[40] = "",next;
/*DataFile存儲(chǔ)候選人信息的文件名,next為是否進(jìn)行下一次投票操作的選項(xiàng)*/
FILE *fp;/*====fp指針指向存儲(chǔ)數(shù)據(jù)的文件名====*/
/*提示用戶輸入要進(jìn)行投票的文件名*/
printf("\nplease input the name of file where data is stored,end with enter key.\n");
gets(DataFile);
/*提示用戶輸入要進(jìn)行投票的文件名*/
while(*DataFile == ('\0'))
{
printf("\nplease input the name of file where data is stored,end with enter key.\n");
gets(DataFile);
}
begin:
/*以讀的方式打開文件,如文件不存在,提示錯(cuò)誤*/
fp=fopen(DataFile,"rb");
if (fp == NULL)
{
printf("\nOpen file %s fail!End with any key\n",DataFile);
perror("Open file fail");
getch();
exit(1);
}
printf("please input the candidate's seatnum which you will vote:");
scanf("%ld",&candidatenum);
printf("the candidate you will vote is:%ld\n",candidatenum);
/*輸入要修改記錄的各項(xiàng)內(nèi)容值,用戶每調(diào)用一次該函數(shù),給該候選人票數(shù)加1*/
Number=candidatenum;
/*將文件中要修改的信息存入結(jié)構(gòu)體數(shù)組*/
recNumber=0;
/*循環(huán)將文件數(shù)據(jù)讀入結(jié)構(gòu)體數(shù)組,
如文件中的數(shù)據(jù)候選人號(hào)和要投票的候選人號(hào)不符,則原樣寫入數(shù)組,
如文件中數(shù)據(jù)的候選人號(hào)和要投票候選人號(hào)匹配,
則根據(jù)其他信息如序號(hào)、姓名、簡介等仍原樣寫入數(shù)組,但票數(shù)加一后寫入數(shù)組,即修改。*/
while((fread(&TmpS,sizeof(candidate),1,fp)) != (int)NULL)
{
if(TmpS.Number!=candidatenum)
{
s[recNumber].Number = TmpS.Number;
strcpy(s[recNumber].Name, TmpS.Name);
strcpy(s[recNumber].intro,TmpS.intro);
s[recNumber].votenum = TmpS.votenum;
recNumber++;
}
else
{
s[recNumber].Number = Number;
strcpy(s[recNumber].Name, TmpS.Name);
strcpy(s[recNumber].intro,TmpS.intro);
s[recNumber].votenum = TmpS.votenum+1;
/*用戶不可以修改候選人姓名、簡介,所以仍為文件中原值,但票數(shù)加一*/
recNumber++;
}
}
fclose(fp);
/*====將修改后的結(jié)構(gòu)體數(shù)組記錄寫入文件====*/
fp=fopen(DataFile,"wb+");
if (fp == NULL)
{
printf("\nSet up file %sfail !end with anykey.\n",DataFile);
perror("Set up fail");
getch();
exit(1);
}
for(i=0; i<recNumber; i++)
{
if(fwrite(&s[i],sizeof(candidate),1,fp)!=1)
{
printf("\nWrite file %s fail!end with anykey.\n",DataFile);
perror("Write file fail!");
getch();
exit(1);
}
}
fclose(fp);
/*====顯示投票后的得票情況====*/
fp=fopen(DataFile,"rb");
if (fp == NULL)
{
printf("\nOpen file%sfail!End with any key \n",DataFile);
perror("Open file fail");
getch();
exit(1);
}
printf("the file after modify is:\n");
printf("\nNumber \tName\tvotenum\n");
while(fread(&TmpS,sizeof(candidate),1,fp) != (int)NULL)
{
if(TmpS.Number!=0)
printf("\n%ld\t%s\t%d\n",TmpS.Number,TmpS.Name,TmpS.votenum);
}
fclose(fp);
/*提示是否進(jìn)行下一次投票*/
printf("\nGo on ?(y/n)");
next=getche();
putchar('\n');
if ( next =='y' || next =='Y') goto begin;
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -