C - 包含整数和字符串的文件(除法问题)

标签 c arrays string file

我有一个任务,我已经工作了几天,我快疯了,谷歌没有帮助,唯一的选择就是在这里问。

我是 C 的初学者。

我有一个文件,普通的 .txt 文件。

Mathematics 5 1 2 3 4 5
Physics 6 1 2 3 4 5 6
Design 7 1 2 3 4 5 6 7

第一个词是“类(class)”,第一个数字是这门类(class)的成绩,例如数学,第一个数字是5,我有5个成绩,1 2 3 4 5,与其他类(class)相同。

我需要创建 3 个不同的数组。

  1. 一系列类(class)(“数学”、“物理”、“设计”),当然不是手工学习,而是从文件中获取所有这些类(class)。

  2. 成绩数量数组(每行第一个数字),

  3. 平均成绩数组(每行除第一个数字外的所有数字),

我的主要问题:

我不能分割我的 .txt 文件,所以我只能得到字符串(数学、物理和设计)。

这是我的代码,是我想出的最合乎逻辑的东西,但不幸的是,fscanf 告诉我无法将 STRING 转换为 INTEGER。

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

int main () {
FILE *fp;
fp = fopen("C:\\Project\\project.txt", "r"); //opening already created file
int grades[500];
char courses[300];

for (int i = 0; i < 300; ++i) {
    fscanf(fp, "%s", &courses[i]);
    if(isdigit(courses[i]))
    fscanf(fp, "%d", &grades[i]);
}

fclose(fp);
return(0);
}

基本上这段代码不起作用。程序将文件中的文本视为 String,我尝试将其作为 char 取出,然后将其发送到其各自的数组,但我实际上做不到。

再一次,首先我需要将这些类(class)名称“数学”、“物理”和“设计”作为字符串,然后再转向数字。

提前致谢

最佳答案

您可以通过使用 fgets() 逐行读取文件并使用 strtok() 提取行中的每个单词来解决此问题。如果我们将分隔符作为空格,strtok 可以将行分隔为单词。下面我给出代码提取 my.txt 中的类(class)和成绩总数以分隔数组。下面给出了我写的一个未经提炼的代码。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
void print_word (char *str ,int i);
static char content[10][40];
char courses[10][20];
int total_num_grades[10];
int line_count =0 ;

void parse_word (char *str ,int line_num)
{
        char *temp ;
        int word_num = 0;
        printf ("Splitting string \"%s\" into tokens:\n",str);
        temp  = strtok (str," "); //taking first word of line
        strcpy(courses[line_num] ,temp);
        temp = strtok (NULL, " "); //taking second word of line
        total_num_grades[line_num] = atoi(temp);


}

void print_result()
{
        printf("courses in the text \n\n");
        for(int i = 0; i <line_count ; i ++)
        {
                printf("%s\n",courses[i]);
        }
        printf ("\n\nnumber of grade array \n\n");
        for(int i = 0;i < line_count ;i ++)
        {
                printf("%d\n",total_num_grades[i]);
        }
}

int main () {
        FILE *fp;
        int len = 0,read = 0;
        fp = fopen("my.txt", "r");
        while ((fgets(content[line_count], 400, fp))) {
                printf("%s", content[line_count]);
                line_count ++;
        }
        for (int line_num = 0; line_num < line_count ; line_num++)
        {
         parse_word(&content[line_num][0],line_num);

        }
        print_result();
        return(0);
}

strtok usage example

关于C - 包含整数和字符串的文件(除法问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292968/

相关文章:

c++ - 错误 : Total size of array must not exceed 0x7fffffff bytes

java - "Object[] x"和 "Object x[]"之间有什么区别吗?

c# - 如何删除字符串?

c - C中的字符串格式化和解析

c++ - 为什么短路模数在 Release模式下不正确?

c - 内存损坏

c - stat 结构的值包含结构丢失

python - 通过 2D 数组作为索引范围对 1D 数组进行 Numpy View

objective-c - 一个奇怪的 C 字符串和 NSString 比较问题

c - 它是向左旋转数组的有效程序吗?