【问题标题】:When should I use scanf with the address of '&' ampersand key?我什么时候应该使用带有“&”和号键地址的scanf?
【发布时间】:2014-09-04 23:17:06
【问题描述】:

我必须读取包含名称和数字的文本文件。名称代表虚拟选举中的候选人(共 7 个),数字代表选民。如果选民编号不在 7 个候选人的范围内,它会被丢弃但仍会被存储。最后,我必须打印出谁赢得了选举以及有多少被破坏的选票的结果。

这是我的文本文件:

Robert Bloom 
John Brown 
Michelle Dawn 
Michael Hall 
Sean O’Rielly 
Arthur Smith 
Carl White 

3 8 1 3 1 6 12 9 6 5 0 2 8 4 
6 6 8 3 2 8 0 12 6 1 8 3 2 2 
3 2 5 7 4 11 8 6 11 12 11 7 5 5 
8 9 10 12 1 3 12 12 9 11 7 9 3 1 
2 10 12 7 11 9 6 6 0 1 10 7 11 2 
8   0 12 8 10 11 2 2 8 4 2 12 3 2 
9   1 4 8 8 7 7 4 12 2 10 10 9 4 
12 9 3 12 0 4 8 0 6 5 9 0 5 3 
11  6   0   3   0 

这就是我对如何正确扫描这些内容感到困惑的地方

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

FILE * data;
int spoilt=0;

typedef struct
{
 int votes;
 char name[20];
}candidates;

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;
    }

}

int processVotes( candidates *electionCandidates, FILE *data )
{
    int i;                                           //tallying votes
    int voter;
    for ( i = 0; i< 365; i++ )
    {
       fscanf( data, "%d", voter );
       if ( voter <= 7&& voter > 0 )
        electionCandidates[voter-1].votes++;
       else
        spoilt++;
    }

                                                    //catcher to grab winner
    int maxValue, winner=0;

    maxValue = electionCandidates[0].votes;
    for( i = 0; i < 7; i++ )
    {
        if( maxValue < electionCandidates[i].votes )
        {
            maxValue = electionCandidates[i].votes;
            electionCandidates[winner] = electionCandidates[i];
        }

    }

    return electionCandidates[winner], maxValue;


}

void printResults( candidates *electionCandidates )
{
    printf("%s won the election with a total of %d votes.\n There was a total of %d spoilt"
            electionCandidates[winner].name, maxValue, spoilt);

}


int main() {
    data = fopen( "elections.txt","r" );
    candidates electionCandidates[7];

    initialize( electionCandidates, data );
    processVotes( electionCandidates, data );
    printResults( electionCandidates );


    fclose( data );
    return 0;
}

【问题讨论】:

  • 它甚至可以编译吗?你在用这个return electionCandidates[winner], maxValue;做什么??您是否尝试返回 2 个值?
  • 这是我认为我搞砸的地方。我试图找到选举的获胜者并返回结构数组中的位置值
  • 只返回获胜者的索引。有了它,您可以直接访问数组中的名称和投票数
  • void initialize( candidates *electionCandidates, FILE *data ) 无法编译。你在使用 C++ 编译器吗?
  • @wildplasser:为什么不能编译?对我来说编译得很好(使用 clang)。

标签: c arrays function struct


【解决方案1】:

使用scanf 时,您必须提供要将结果扫描到的变量的地址。使用&amp; 运算符提供地址。此外,最好检查scanf 的结果,以确保它成功扫描了您所要求的内容。 scanf 将始终返回成功扫描的元素数,除非发生 I/O 错误,在这种情况下它将返回一个负数。

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

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

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 接受&amp;voter 并随后用适当的数据填充voter 变量(如果可以的话)。

【讨论】:

  • 即使我尝试使用这样的 getwhile 循环,我也无法在 Dev C++ 中编译它:getchar();返回0; }
  • 桌面\mikehomework\Makefile.win [构建错误] [theElection.o] 错误 1
  • @user3498869:一定有比某处更具描述性的错误......它对我来说编译得很好(我使用的是clang而不是dev-c ++,但我启用了所有警告和迂腐模式,但仍然没有错误)。您确定您的源代码与上述匹配吗?
  • 哇,我又来回答我的问题了,其中一些我很尴尬我问了。
  • @Fappycow 永远不要感到尴尬,而只是将它作为你所学知识的参考点。
猜你喜欢
  • 2013-08-26
  • 1970-01-01
  • 2011-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 2023-04-02
  • 2012-09-22
相关资源
最近更新 更多