如何将文件中的值存储到数组中?

How do I store a value in a file to an array?

我有一个 txt 文件,如下所示:

1:0
2:0
3:1
4:0
...
99:1
100:1

我想将 10 存储在一个数组 (slot[]) 中,(不管 '[=16= 的左边是什么]'s), 但我不知道怎么做。这是我的代码片段:

while((ch=fgetc(fptr)) != EOF) 
{
     if(ch == ':')
     {
       slot[j] = fgetc(fptr);       //saves the character right after ":"into slot[j]?
       j++;
     }
}

我知道它比这更复杂,因为它不起作用。找了半天也没找到,可能是没有搜索到正确的词吧

我该如何解决这个问题?

提前致谢。

它看起来很简单,只是做了一些小的改动,因为你的规格说明右边总是有 1 个数字,并且总是 01,像这样应该可以做到:

if (fptr != NULL)
{
    int ch;
    int j = 0;

    while ((ch = fgetc(fptr)) != EOF)
    {
        if (ch == ':') 
        {
            if ((ch = fgetc(fptr)) != EOF) // get digit after :
            {
                slot[j++] = ch - '0';  // for int array *
                //slot[j++] = ch;      // for char array
            }
            else
            {
                break;
            }
        }
    }
}

或者,使用 fgets 的更稳健的方法:

if (fptr != NULL)
{
    char temp[100]; // must be large enough to hold the line
    char *ch;
    int j = 0;

    while (fgets(temp, sizeof temp, fptr)) // read whole line
    {
        ch = strchr(temp, ':'); // find :
        if (ch != NULL && (ch[1] == '1' || ch[1] == '0'))
        {
            // add next digit to slot[] if it's 1 or 0
            slot[j++] = ch[1] - '0'; // or remove - '0' for char slot[]
        }
    }
}

需要 string.h header strchr

* 如果您想了解有关字符到数字转换的更多信息,请检查此 post:

Why is there a need to add a '0' to indexes in order to access array values?

它没有按照您的预期运行的原因是因为您正在阅读字符并期望它们是数字。 C 中的字符具有整数值。该映射称为 ASCII(在 Internet 上搜索“ASCII table”)。大写字母从 65 开始,小写字母从 97 开始,数字从 48 开始。所以,如果“0”是 48,“1”是 49,你可以将“0”和“1”改为 0 和1分别减去48:

slot[j] = fgetc(fptr) - 48;

这行得通,但稍后您会忘记 48 的含义,必须再次查看 ASCII table,因此您应该使用字符:

slot[j] = fgetc(fptr) - '0';

它做同样的事情,但很明显你为什么要减去一个值。

您可以使用相同的技巧将大写字母转换为小写字母:

if (ch >= 'A' && ch <= 'Z') ch += 32;

或小写转大写:

if (ch >= 'a' && ch <= 'z') ch -= 32;

但是,当然,还有称为 tolower()toupper() 的库函数,它们更具表现力,这就是为什么没有人这样做的原因。