【问题标题】:How do you read the integers from a text file of both characters and integers?如何从字符和整数的文本文件中读取整数?
【发布时间】:2018-10-25 00:24:40
【问题描述】:

我在从文本文件中读取和存储最后一组值时遇到问题。例如,假设这是打印在一个文本文件中:

身份证等级
AA22 12
BB33 13
DD44 14

如何只读取学生的成绩并将其存储为整数以便进行计算?

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

FILE *fp;
int counter;

int main () {
    fp = fopen ("nameoffile.txt", "r");
    int line[50];
    while (fgets(line, 50, fp) != EOF) {
       counter = counter + line;
    }
   printf("The total amount is %d", counter);
}

它最初是写的,提出的问题与给出的示例相似。我真的更关心逻辑。

【问题讨论】:

  • “我遇到了麻烦”,但我没有看到一段代码会带来麻烦。你能发布你到目前为止所做的事情吗?
  • 能否提供您的示例代码??
  • 正如 WedaPashi 所说,只需向我们展示您的一些代码,即使它不是那么好,我们也会为您指明正确的方向。
  • 没有任何信息,我们只能猜测您需要什么,我认为您需要了解scanf
  • 欢迎来到 Stack Overflow。请尽快阅读 AboutHow to Ask 页面,但更重要的是,请阅读有关如何创建 MCVE (minimal reproducible example) 的信息。

标签: c integer character


【解决方案1】:

这里有一些代码可以帮助您入门。您可以以此为基础构建适合您的逻辑。

必须进行许多错误检查,但我将此留给您,以找出需要改进的地方。

我建议您首先分析它并了解究竟发生了什么,因为您的代码存在许多基本错误。

int main(void)
{
    FILE *fp;

    fp = fopen("nameoffile.txt", "r");

    char line[200];
    char ids[20][20];
    int grades[20];
    int cnt;

    cnt = 0;

    while (fgets(line, sizeof(line), fp) != NULL)
    {
        if(cnt)
            sscanf(line, "%s %d", ids[cnt - 1], &grades[cnt - 1]);

        cnt++;
    }

    printf("ID GRADE\n");
    for(int i = 0; i < cnt - 1; i++)
    {
        printf("%s %d\n", ids[i], grades[i]);
    }

    return 0;
}

【讨论】:

    【解决方案2】:

    您似乎知道如何编码,但在分解项目时遇到了麻烦。分解项目成为逻辑。分解项目然后用谷歌搜索你不理解的每个点是有帮助的。原因很明显,您的项目对您来说是信息过载。下次试试吧。

    当然,这需要做很多事情,但从长远来看,使用这种方法可以节省大量时间。 ✔︎

    细分

    • 读取文件

    • 确定“成绩”列。

    • 仅读取“成绩列”下的值。

    • 确保值的字符都是isdigit()

    • 将值转换为整数:atoi() 然后将这些值添加到数组中,以供以后使用。 to carry out calculations 如你所说。

    研究细分

    读取文件

    => C Read Text File ... Now you have access to each line

    确定“成绩”列

    => multiple spaces to only one => by doing this step, its now easy to identify what your Columns "ID Grade ... ..." are delimited by.

    => Find a substring of a string in C ... Now you know you're currently on the line of your HEADERS ... You'll use this headers to figure out what column your grades are under.

    => 通过使用伟大的互联网为您提供的strstr() 示例,您现在可以随意使用“等级”一词的起始字符的索引号。

    => 幸运的是,您已经将列分隔符设置为一个空格,所以现在您循环遍历字符串,直到达到该索引号。

    => 但是这样做时,您需要计算遇到的空格数量。因为当您的循环到达索引号时,您将获得成绩的列号 - “成绩”,实际上只是空格数。

    确保值的字符都是数字

    isdigit()

    => 循环到您的成绩值所在的列...您可以这样做,因为您知道列号和列分隔符。

    => 当你到达字符串中的那个点时,开始检查isdigit() 之后的每个字符。我所说的“之后的每个字符”是指所有字符,直到你到达一个空格。

    => 如果你遇到一个不是数字的字符,那么会抛出一些语法错误或者比这更酷的东西。你的程序!

    => 既然您知道成绩值都是数字,那么您想要 atoi() 那个坏男孩。但如何? something like this... ... this example code is how to get that value out of the whole string. Now you need to take that value in atoi(value).

    => 然后您将atoi(value) 的返回值添加到您的值中

    祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2019-05-12
      • 2013-03-01
      • 2014-11-16
      • 1970-01-01
      相关资源
      最近更新 更多