如何使计数器在此C程序中工作? [英] How to I get the counter to work in this C program?

查看:79
本文介绍了如何使计数器在此C程序中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

int main()
{
    FILE *myFile;
    int x, b, n = -1, i, count = 1;
    int num[101];

    myFile = fopen("a.txt", "r");
    b = fscanf(myFile, "%d", &x);
    while (b != -1){
        n++;
        num[n] = x;
        b = fscanf(myFile, "%d ", &x);
    }
        for (int i = 0; i <= n; i++){
            printf("%d ", num[i]);
        }
        printf("\n");
        for(int i = 1; i <= 100; i++){
        if(num[i] == i) {
            printf("%i has occurred: %d times\n", i, count);
            count++;
        }
    }
        fclose(myFile);
}

我有一个面向Unix和C编程课程的项目,我和星期一无法弄清楚计数器的工作方式。本质上,我们正在学习如何在C中使用数组,在C中使用指针以及如何使用文件输入/输出。在作业中,我们必须从文本文件中获取输入,并且必须将文本文件中的所有值作为数组打印出来。那是容易的部分。困难的部分是对数组中的每个特定变量进行计数。我认为用Java进行此操作会更容易,因为这是我们参加此200级课程之前所做的。但是,我们无法在Java中执行此操作,因此我不确定如何继续。

I have a project for a Unix and C programming class due on Monday and I cannot figure out how to work the counter. Essentially, we're learning about using Arrays in C, pointers in C, and using File Input/Output. On our homework, we have to take input from a text file, and we have to print out all the values in the text file as an array. That's the easy part. The hard part is counting each specific variable in the array. I feel it would be easier to do this in Java as that's what we've been doing before taking this 200 level course. However, we cannot do this in java, thus I am not sure how to proceed.

您能帮个兄弟吗?

推荐答案

使用过多的变量会使您感到困惑。您需要做的就是将每个整数读入下一个数组元素,同时元素的数量在数组范围内。您需要数组和一个计数器。

You are confusing things by using too many variables. All you need to do is read each integer into the next array element while the number of elements is within your array bounds. You need the array and a single counter.

在研究该问题之前,请先简短地学习一下:不要使用 Magic-Numbers 't 硬编码文件名。相反,如果需要常量,请 #define 一个,例如

Before looking at that problem, a quick lesson: Don't use Magic-Numbers and don't Hardcode-Filenames. Instead, if you need a constant, #define one, e.g.

#define NELEM 101   /* if you need a constant, #define one (or more) */

然后在代码中使用常量来调整数组大小并设置所需的其他限制,例如

Then use the constant within your code to size your array and set any other limits needed, e.g.

    int num[NELEM];     /* array */

    /* read integers while n < NELEM && good read */
    while (n < NELEM && fscanf(myFile, "%d", &num[n]) == 1)
        n++;    /* advance counter */

main()函数接受参数, int main(int argc,char ** argv),将文件名作为参数传递给 main()或以文件名作为输入,例如

The main() function takes arguments, int main (int argc, char **argv), pass the filename to read as an argument to main() or take the filename as input, e.g.

    /* read filename from 1st argument (stdin by default) */
    FILE *myFile = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!myFile) {  /* validate myfile is open for reading */
        perror ("fopen-myfile");
        return 1;
    }

这样,您不必每次都要更改重新编译输入文件。

That way you don't have to recompile every time you want to change the input file.

现在读取。每次读取输入时,都必须在成功完成读取当前值(或最好是一行)后再进行下一次读取。在这种情况下,如上所示,您仅需要满足两个条件:(1)您尝试读取的值不会超过数组中存储的值,(2)使用任何 Xscanf( )函数,则返回值等于预期的转换次数。 (您也可以简单地连续循环,检查循环内的返回值,并在满足退出条件之一时中断循环)

Now to the read. Whenever you are reading input, you always condition the next read on the successful completion of reading the current value (or line preferably). In that case as shown above, you simply have 2-conditions to meet, (1) you do not try and read more values than you can store in your array, and (2) when using any Xscanf() function, that the return is equal to the number of conversions anticipated. (you can also simply loop continually, checking the return within the loop and breaking the loop when one of your exit conditions is met)

在您的情况下:

    int n = 0;          /* counter */
    int num[NELEM];     /* array */
    /* read filename from 1st argument (stdin by default) */
    FILE *myFile = argc > 1 ? fopen (argv[1], "r") : stdin;
    ...
    /* read integers while n < NELEM && good read */
    while (n < NELEM && fscanf(myFile, "%d", &num[n]) == 1)
        n++;    /* advance counter */

上面的代码将整数值读入数组,直到(1)数组已满,或(2)第一次失败的转换发生(可以在 matching-failure EOF 上)

The code above reads integer values into you array until (1) the array is full, or (2) the first failed conversion occurs (which can be on either a matching-failure or EOF)

此时您已完成。您将值存储在 num 中,并将值计数存储在 n 中。要输出值,只需从 0 循环到 n-1 ,即可覆盖您的填充元素。示例:

You are done at that point. You have the values stored in num and you have the count of values stored in n. To output the values, simply loop from 0 to n-1, which covers your filled elements. Example:

    for (int i = 0; i < n; i++) {   /* output in 10-col format */
        if (i && i % 10 == 0)
            putchar ('\n');
        printf (" %6d", num[i]);
    }
    putchar ('\n');     /* tidy up with \n */

注意:循环是重要的部分,您可以按自己的喜好格式化输出。它只显示在10列中,每个值都是6位数宽(包括 +/- ))

(note: the loop is the important part, you can format how it is output as you like. It is just shown in 10-columns with each value being 6-digits wide (including +/-))

完整的示例可能是:

#include <stdio.h>

#define NELEM 101   /* if you need a constant, #define one (or more) */

int main(int argc, char **argv) {

    int n = 0;          /* counter */
    int num[NELEM];     /* array */
    /* read filename from 1st argument (stdin by default) */
    FILE *myFile = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!myFile) {  /* validate myfile is open for reading */
        perror ("fopen-myfile");
        return 1;
    }

    /* read integers while n < NELEM && good read */
    while (n < NELEM && fscanf(myFile, "%d", &num[n]) == 1)
        n++;    /* advance counter */

    if (myFile != stdin)    /* close file if not stdin */
        fclose (myFile);

    for (int i = 0; i < n; i++) {   /* output in 10-col format */
        if (i && i % 10 == 0)
            putchar ('\n');
        printf (" %6d", num[i]);
    }
    putchar ('\n');     /* tidy up with \n */
}

示例用法/输出

读取具有61个整数的文件:

Reading a file with 61 integer values:

$ ./bin/fscanfintarray dat/n_61_ints.txt
     60   1984  -7093   1236  -3680  -3184  -3936   6671   8906  -5207
  -9698   3681    952   -137    664   8798    -30  -6392   7155   7797
  -7665   4829  -4115   -435   7194   -279  -5619  -5154  -3755  -3818
  -7186  -8420  -4602  -4279  -9952   1718   2537  -3888  -1611   8676
    905   5924   2357  -8143   3019    253  -2113  -7011  -8907  -4958
  -1982  -6572  -2897   3904  -9774  -5703  -6375  -5393   6375   7102
    789

仔细检查一下,如果您还有其他疑问,请通知我。

Look things over and let me know if you have any further questions.

这篇关于如何使计数器在此C程序中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆