c语言scanf的lf与hf,什么时候应该使用scanf的地址'&'和号键?

使用scanf,你必须提供的的地址您想要将结果扫描到的变量。通过使用&运营商提供地址。此外,检查scanf的结果以确保它成功扫描了您要求的内容是个不错的主意。 scanf将始终返回成功扫描的元素数量,除非发生I/O错误,在这种情况下,它将返回负数。

这是你的程序的固定,注释版本:

#include

#include

#include

typedef struct

{

int votes;

char name[20];

}candidates;

// specify a new type to hold the election result data

typedef struct

{

int winner;

int maxVotes;

int spoilt;

} electionResult;

void initialize(candidates *electionCandidates, FILE *data)

{

int i;

for(i=0; i<7; i++)

{

fscanf(data, "%[^\n]%*c", electionCandidates[i].name);

printf("%s\n", electionCandidates[i].name);

electionCandidates[i].votes=0;

}

}

// This function can now return more than one value, because we've wrapped

// the relevant info into a structure called "electionResult"

electionResult processVotes(candidates *electionCandidates, FILE *data)

{

// declare the election result struct here (which we fill with data)

// we initially set all values to 0

electionResult er = {0, 0, 0};

int i; //tallying votes

int voter;

for (i = 0; i< 365; i++)

{

// scan the vote by providing the address of voter (using &)

int result = fscanf(data, "%d", &voter);

if (result == 1)

{

if (voter <= 7&& voter > 0)

electionCandidates[voter-1].votes++;

else

er.spoilt++;

}

}

er.maxVotes = electionCandidates[0].votes;

for(i = 0; i < 7; i++)

{

if(er.maxVotes < electionCandidates[i].votes)

{

// update the values in the election result struct

er.maxVotes = electionCandidates[i].votes;

er.winner = i;

}

}

return er;

}

// this function now prints the result of the election by accepting an "electionResult" struct

void printResults(candidates *electionCandidates, electionResult er)

{

printf("%s won the election with a total of %d votes.\n There was a total of %d spoilt",

electionCandidates[er.winner].name, er.maxVotes, er.spoilt);

}

int main() {

FILE *data = fopen("elections.txt","r");

candidates electionCandidates[7];

electionResult er;

initialize(electionCandidates, data);

er = processVotes(electionCandidates, data);

printResults(electionCandidates, er);

fclose(data);

return 0;

}

一些提示:

您不能访问其他功能声明的变量。您必须从一个函数中返回所需的数据并将其提供给另一个函数。

避免在文件范围声明变量(如果可以的话)。对于这样简单的程序来说,这并不是什么大问题,但总的来说,使用全局变量往往会变得非常麻烦。

,除非你在一个结构包裹起来的值不能从一个函数返回多个值,就像上面,或者,你已经接受函数指针向将保存结果的对象,类似于fscanf接受&voter并随后用适当的数据填充voter变量(如果可以的话)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值