作为参数传递时数组更改

时间:2017-11-07 23:07:29

标签: c arrays

我试图将文件中的负数和正数读入数组。

这是我的代码

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

void printData(int data[]) {
  for (int i = 0; i < 21; i++) {
    printf("%d\n", data[i]);
  }
}

void findMaximumDataValue(int data[]) {
  int max = -INFINITY;
  for (int i = 0; i < 21; i++) {
    if (data[i] > max) {
      max = data[i];
    }
  }
  printf("The maximum value in the file is: %d\n", max);
}

void userInterface(int data[]) {
  while(1) {
    char choice;
    printf("a) Print out the values\n");
    printf("b) Find the maximum Value\n");
    printf("c) Calculate the RMS (root mean square)\n");
    printf("d) Count the number of negative values\n");
    printf("e) Exit Back to Main Menu\n");
    printf("Enter selection: ");
    scanf("%s", &choice);
    printf(" %c", choice);
    switch (choice) {
      case 'a': {
        printData(data);
        break;
      }
      case 'b': {
        findMaximumDataValue(data);
        break;
      }
      case 'e': {
        return;
      }
    }
  }
}

void dataTxtFunctions() {
  FILE* fp;
  int data[21];
  // Failed to open file
  if ( !(fp = fopen("data.txt", "r")) ) {
    printf("%s\n", strerror(errno));
    return;
  }
  for (int i = 0; i < 21; i++) {
    fscanf (fp, "%d", &data[i]);
  }
  fclose(fp);
  userInterface(data);
}


int main() {
  dataTxtFunctions();

}

当我对我的data.txt运行此代码时,我得到了

1
6
4
5
5
9
12
14
15
-17
-19
21
-23
0
37
0
-31
32
34
-37
-39
0
a) Print out the values
b) Find the maximum Value
c) Calculate the RMS (root mean square)
d) Count the number of negative values
e) Exit Back to Main Menu
Enter selection: a
a0
0
0
0
0
0
0
0
192327
0
0
0
8
48
1497598080
32767
1
6
4
5
5

第一部分,在菜单显示文件中的正确值之前,然而,在进行选择并传递数组时,数据已更改。

为什么?

2 个答案:

答案 0 :(得分:1)

您有大量小错误。 (在代码中的注释中说明)。您的主要问题是了解声明data的位置和方式,以及如何将文件中的值作为菜单系统的一部分从data获取。虽然您可以在data函数中声明数组userinterface,但通常您需要在main()(或调用函数)中声明变量,然后将它们作为参数传递(正确限定) )任何需要它们的功能。

作为对如何填充data的误解的一部分,您的void dataTxtFunctions()或多或少随机地漂浮在您的代码中,而不是附加在任何地方。这个名字也暗示了一个大的:

&#34;我不知道自己要做什么,所以我称之为通用的dataTxtFunctions并希望它能够自行运行不知何故?&#34;

注意:编码方法永远不会成功......)

你需要的是一个readdata函数来提示文件名,打开并验证文件,然后从文件中读取整数,提供有意义的读取整数数的返回(或{{1}表示失败)。这样您就可以创建一个0菜单项来处理这些操作。

(不要在代码中硬编码值或名称(例如" r) Read data from file\n"),幻数魔术字符串限制代码的有用性并使其成为可能很难维护)

以下评论中提供了其余建议。以下示例可与您的data.txt一起使用(我使用您在问题中显示的前22个值作为下面的输入文件)。如果我理解你想要完成的任务,你可以做以下事情:

data.txt

另外,关于样式的注释,C通常会避免使用 camelCase MixedCase 名称,而是使用所有小写名称来保留变量和函数,为常量和宏保留大写。由于它是风格,它完全取决于你,但它确实说明了你的代码。

示例使用/输出

#include <stdio.h>
#include <limits.h>

#define MAXN 256    /* if you need a constant, define one */
                    /* don't skimp on array sizes */

/* empty any characters that remain in stdin -- following scanf */
void empty_stdin()
{
    for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
}

/* print values in data (both data and number of values are const) */
void printdata (const int *data, const size_t n)
{
    for (size_t i = 0; i < n; i++)
        printf ("data[%3zu]: %d\n", i, data[i]);
}

/* find/return max value in data (data and n are const) */
int findmaxdatavalue (const int *data, const size_t n)
{
    int max = INT_MIN;      /* use INT_MIN from limits.h */

    for (size_t i = 0; i < n; i++)
        if (data[i] > max)
            max = data[i];

    return max;     /* provide a return to gauge success/failure */
}

/* prompt for filename, read up to max values from file.
 * returns number of values read (0 indicates failure).
 */
size_t readdata (int *data, size_t max) 
{
    int tmp;                    /* temporary value to validate read */
    char filenm[PATH_MAX] = ""; /* buffer to hold filename */
    FILE *fp = NULL;            /* FILE stream pointer */
    size_t n = 0;               /* number of values read */

    for (;;) {      /* loop until valid filename provided or EOF */
        int rtn;

        printf ("\nenter filename: ");
        /* if EOF, user canceled with ctrl+d (ctrl+z on windoze) */
        if ((rtn = scanf ("%[^\n]", filenm)) == EOF)
            return 0;
        empty_stdin(); /* remove '\n' (or can chars beyond PATH_MAX) */

        if (rtn == 1)  /* if return 1, good string in filenm */
            break;
        /* otherwise, handle error */
        fprintf (stderr, "error: invalid input - filename.\n");
    }

    if (!(fp = fopen (filenm, "r"))) {  /* validate open */
        fprintf (stderr, "error: file open failed '%s'\n", filenm);
        return 0;
    }

    /* read up to 'max' values from file */
    while (n < max && fscanf (fp, "%d", &tmp) == 1)
        data[n++] = tmp;

    fclose (fp);

    return n;   /* return number of integers read */
}

void userinterface (int *data, size_t *n, size_t max)
{
    while (1) {     /* loop continually */

        char choice = 0;
        int rtn;    /* you only need 1 printf */
        printf ("\n r) Read data from file\n"
                " a) Print out the values\n"
                " b) Find the maximum Value\n"
                " c) Calculate the RMS (root mean square)\n"
                " d) Count the number of negative values\n"
                " e) Exit Back to Main Menu\n\n"
                "Enter selection: ");

        if ((rtn = scanf ("%c", &choice)) == EOF)
            return;
        empty_stdin();      /* empty '\n' (and any other chars) */

        if (rtn != 1 || /* validate return and proper choice */
            (choice != 'r' && (choice < 'a' || 'e' < choice))) {
            fprintf (stderr, "error: invalid input - choice.\n");
            continue;   /* on bad choice, redisplay menu */
        }

        if (!*n && choice < 'e') {  /* if no data, only 'e' or 'r' valid */
            fprintf (stderr, "error: data is empty.\n");
            continue;   /* data empty, redisplay menu */
        }

        switch (choice) {   /* handle choice */
            case 'a':
                printdata (data, *n);
                break;
            case 'b':
                printf ("max value: %d\n", findmaxdatavalue (data, *n));
                break;
            case 'c':
                fprintf (stderr, "RMS not yet implemented.\n");
                break;
            case 'd':
                fprintf (stderr, "Negative count not yet implemented.\n");
                break;
            case 'e':
                return;
                break;
            case 'r':   /* read data, handle error, warn if max values read */
                if (!(*n = readdata (data, max)))
                    fprintf (stderr, "error: nothing read from file.\n");
                else if (*n == max)
                    fprintf (stderr, "warning: data is full.\n");
                break;
            default : fprintf (stderr, "error: something wrong with switch.\n");
                break;
        }
    }
}

int main (void) {

    int data[MAXN] = {0};   /* declare values in main() */
    size_t max = MAXN,
        n = 0;

    userinterface (data, &n, max);  /* pass to userinterface */

    printf ("\nsuccessfully processed '%zu' integers from file.\n", n);

    return 0;
}

仔细看看,如果您有其他问题,请告诉我。

答案 1 :(得分:0)

这是从文件中读取的正确方法: while(fread(&amp; data [i],sizeof(int),1,fp));