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

时间:2018-11-14 03:53:43

标签: 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

第一个单词是一个“课程”,第一个数字是该课程的年级数量,例如数学,第一个数字是5,而我有5个年级,即1 2 3 4 5,与其他课程相同。 / p>

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

  1. 一系列课程(“数学”,“物理”,“设计”),当然不是用手,而是从FILE中获取所有这些内容。

  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取出,然后再将其发送到其各自的数组中,但实际上我做不到。

再一次,首先我需要将那些课程名称,“数学”,“物理”和“设计”作为字符串,然后再转到数字上。

预先感谢

2 个答案:

答案 0 :(得分:0)

fscanf(, "%s", buffer)读取一个字符串,直到一个空格,然后将结果放入缓冲区。

第一次致电fscanf(fp, "%s", courses);将阅读数学并将单词存储在课程数组中。 第二次通话fscanf(fp, "%s", courses);将读取5并将字符存储在课程数组中

您将需要将字符转换为数字,检查换行符,处理错误-如果输入字符不是数字怎么办,等等?

您的第一个呼叫fscanf(fp,“%s”,&courses [i]);获得课程名称。循环的第二次迭代将使您在课程中获得“ M1thematics”。您不需要[i]部分。您需要更改循环。那那个300号是什么?

另一个提示:&courses [0]指向数组的开头,与course相同。 &courses [1]指向课程中的第二个元素。

其余的取决于您。

答案 1 :(得分:0)

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

#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);
}

Angular