0

我如何使用fscanf(或处理stdin文本文件中的 s 的任何其他函数)扫描具有相同长度的特定整数组,并将它们放在同一个数组中,但同时忽略较短的整数超出要求

这是 txt 文件的外观:

63001234 1 1 -1 - - 0 1 1 1 - - 0
63001230 1 1 1 1 1 1 1 1 1 1 1 1
63001432 -1 -1 - - - - - - - - - -
63000176 - - 1 0 0 1 0 0 1 1 1 1

我需要将 63... 数字存储在一个 int 数组中,并将 '1'、'-1'、'0' 和 '-' 存储在另一个 char 数组中。

这是我的扫描和测试功能合二为一

int main() {

    printf("insert the name of the txt file you want to scan from: ");
    char fileopen [100];
    scanf("%s", fileopen);

    int Students [250];
    char Grades [250] [12];

    FILE *fop = fopen(fileopen ,"r");
    if(fop == NULL){
        printf("Error");
        EXIT_FAILURE;
    }
    int counter = 0;

    //read file
    while(1){
        if(fscanf(fop,"%d",&Students[counter]) == EOF){
            break;
        }
        for(int j = 0; j < 12; j++){
            fscanf(fop," %c",&Grades[counter][j]);
        }
        fscanf(fop,"\n");
        counter++;

    }

    counter = 0;
    //test what has been written in the arrays 
    while(counter <= strlen(Students)){

       printf("%d", Students[counter]);
       for(int j = 0; j < 12; j++){
            printf(" %c", Grades[counter][j]);
        }
        counter++;
        printf("\n");
    }

}
4

1 回答 1

0

您可以直接读取整数和字符,而不是使用数字检查:

// You can use dynamic memory allocation here instead, or an appropriate max size.
// I used 100 because this is a template.
int numbers[100];
int chars[100][12];

char* line = (char*)malloc(100);

int i = 0;
while (true)
{
    /* Read line into buffer */
    if ((fgets(line, 100, file) == NULL) || ferror(file) || feof(file))
    {
        break;
    }

    /* Skip empty lines */
    if (strcmp(line, "\n") != 0)
    {
        continue;
    }

    /* Scan the integer */
    if (i == 0) {
        sscanf(line, "%d", &numbers[0]);
    } else {
        sscanf(line, "\n%d", &numbers[i]);
    }

    /* Scan the 12 characters */
    for (unsigned int j = 0; j < 12; ++j)
    {
        sscanf(line, " %c", &chars[i][j]);
    }

    i++;
}
于 2013-03-27T15:00:44.170 回答