C 程序因调用函数而停止运行?

标签 c function

这可能很难解释。我正在开发一个程序,该程序接受一个包含数字的文件。前两个数字是矩阵行的维度,然后是列的维度。其余数字是矩阵的元素。我遇到的问题是,在我创建了一个函数来读取给定的 c 样式字符串中的数字后,程序停止执行任何操作。它编译并运行,但什么也没做,甚至没有打印 main 之后的第一行。

proj2.c

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

float readNum(char* buffer, int *pos);

int main(){


    char buffer[512];

    printf("Enter File Name: ");
    //char* fileName = fgets(buffer, sizeof(buffer), stdin);
    FILE* file = fopen("matrix.txt", "r");
    if(file == NULL){
        printf("ERROR COULD NOT OPEN FILE\n");
        exit(1);

    }
    int row = 0;
    int col = 0;
    int rowcheck = 0;
    int colcheck = 0;
    int matrixcheck = 0;
    while(!feof(file)){
        printf("HELLO");

        if(fgets(buffer,sizeof(buffer),file) != NULL){
            //position of current character
            int pos = 0;

            //current character
            char current;

            //loop to determine the dimensions of the matrix
            if(colcheck == 0 && rowcheck == 0){
                while(colcheck == 0 || rowcheck == 0){
                    //set current character
                    current = buffer[pos];
                    //determine if current character is a number and that the nex character is a space
                    //for single digit row dimensions
                    if(current >= '0' && current <= '9'  && buffer[pos+1] == ' ' && rowcheck == 0){
                        row += current - '0';
                        rowcheck = 1;
                    }
                    //if not single digit row dimension add the current character times 10
                    //and repeat loop to obtain the second digit
                    else if (buffer[pos+1] >= '0' && buffer[pos+1] <= '9' && rowcheck == 0){
                        row += (current - '0') * 10;
                    }
                    //for columns check if current character is a number and if the next character is space or newline
                    //and that row has already been checked
                    else if(current >= '0' && current <= '9' && (buffer[pos+1] == ' ' || buffer[pos+1] == 10) && rowcheck == 1){
                        col += current - '0';
                        colcheck = 1;
                    }
                    //final check for if columns is double digit so check if next char is a number and that current char is
                    //not a space
                    else if(buffer[pos] != ' ' && buffer[pos+1] >= '0' && buffer[pos+1] <= '9' && rowcheck == 1){
                        col += (current - '0' ) * 10;
                    }
                    pos++;
                    printf("rows: %d  cols: %d", row,col);
                }
            }
            //condition to ensure columns and rows have been determined
            else if(colcheck == 1 && rowcheck == 1){
                //loop to find the elements of the matrix
                while(matrixcheck == 0){
                    current = buffer[pos];
                    if(buffer[pos + 1] != 10){
                        if((current >= '0' && current <= '9') || current == '-' || current == '.'){
                            float num = readNum(buffer, &pos);
                            printf("number: %f", num);
                        }
                    }
                }

            }
        }
    }
    fclose(file);
}

和readNum.c

#include <stdio.h>
#include <math.h>

float readNum(char* buffer,int *pos){
    int negative = 1;
    int y = 0;
    float number = 0;
    if(buffer[*pos] == '-'){
        negative = -1;
        (*pos)++;
    }
    while(buffer[*pos + y] >= '0' && buffer[*pos + y] <= '9'){
        y++;
    }
    for(int z = 0; z < y; z++){
        number += (buffer[*pos + z] - 48) * pow(10, y - z - 1);
    }
    *pos += y;
    if(buffer[*pos] == '.'){
        (*pos)++;
        int d = 0;
        while(buffer[*pos + d] >= '0' && buffer[*pos + d] <= '9'){
            if(buffer[d + *pos] == '.'){
                printf("ERROR: multiple decimals in an element");
            }
            d++;
        }
        for(int z = 0; z < d; z++){
            number += (buffer[z + *pos] - '0') * pow(10, -z - 1);
        }
        pos += d;
    }
    return number * negative;
}

注释掉这些行

float num = readNum(buffer, &pos);
printf("number: %f", num);

允许程序正常运行,但是取消注释它们它只是停止执行任何操作,在 Eclipse 中控制台只是保持空白运行某些内容或其他内容,我稍后终止它,因为什么也没有发生,甚至没有打印第一行.

这是一个正在读取的示例文件 3 2 56 12 98 25 34.5 45

提前谢谢

解决方案已经找到,我不确定每个人是否都明白程序中到底发生了什么。 main 根本不会运行,第一行不会打印任何内容。解决方案是在第一个打印语句之后使用 fflush(stdout) 。

最佳答案

逐个字符地解析文件是非常复杂的,当你 试图读取 float 。使用标准库提供的函数。

您的代码可能会产生未定义的行为,因为您没有检查边界 缓冲区,例如:

if(current >= '0' && current <= '9'  && buffer[pos+1] == ' ' && rowcheck == 0){
    row += current - '0';
    rowcheck = 1;
}

您从不检查是否读取了 '\0' 终止字节并继续递增 posbuffer[pos+1] 可能会超出限制访问。我也不懂 你是如何真正解析维度的。这就是为什么我告诉你,不要重新发明 轮子,使用您可以使用的工具。

你说尺寸在第一行,那么你可以得到 这样做的尺寸:

char buffer[512];
if(fgets(buffer, sizeof buffer, file) == NULL)
{
    fprintf(stderr, "File is empty\n");
    flcose(file);
    return 1;
}

size_t cols,rows;

if(fscanf("%zu %zu", &rows, &cols) != 2)
{
    fprintf(stderr, "Invalid file format, cannot get columns and rows\n");
    fclose(file);
    return 1;
}

if(rows == 0 || cols == 0)
{
    fprintf(stderr, "Invalid dimension %zux%zu\n", rows, cols);
    fclose(file);
    return 1;
}

现在,您可以像这样解析文件:

float matrix[rows][cols] = { 0 };

for(size_t i = 0; i < rows; ++i)
{
    if(fgets(buffer, sizeof buffer, file) == NULL)
    {
        fprintf(stderr, "End of file reached before filling matrix\n");
        fclose(file);
        return 1;
    }

    int pos;
    char *scan = buffer;

    for(size_t j = 0; j < cols; ++j)
    {
        if(sscanf(scan, "%f%n", matrix[i] + j, &pos) != 1)
        {
            fprintf(stderr, "Invalid format at line %zu\n", i+2);
            break; // continue parsing with the next line
        }

        scan += pos;
    }
}

fclose(file);

printf("matrix[%zu][%zu] = %f\n", rows/2, cols/2, matrix[rows/2][cols/row]);

这段代码更加健壮,因为它检查函数是否正常工作 故意的。如果在填充矩阵之前无法读取更多行,那么您 可以返回错误信息并结束程序。如果线路没有 正确的格式,我忽略该行并且该行填充有 0,同时也 打印错误消息。如果行数多于行数,则忽略它们 并且你不会溢出缓冲区。意图也更加明确 更容易理解我在做什么。

就像我一开始说的,使用标准C提供的函数 图书馆比再次发明轮子要好。你的代码是 复杂且难以阅读。

另请参阅why is while(feof) always wrong 。管理末端更容易 使用fgets时的文件,因为当没有更多数据可以时,fgets返回NULL 由于 I/O 错误或文件到达 EOF,而无法读取。那是 为什么我上面的例子总是检查fgets的返回值。注意我的使用方式 %n 采用 scanf 格式:%n 返回消耗的字符数 远离输入,在循环中使用 sscanf 时这是一个很好的信息。我也 检查 scanf 是否未返回匹配元素的数量(请注意 %n 不会增加匹配元素的数量)。欲了解更多信息 这请参阅documentation of scanf .

关于C 程序因调用函数而停止运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49040946/

相关文章:

c - GCC 4.4.3 中的功能特定优化

python - 如何使另一个函数中的函数同时退出这两个函数?

PHP,函数中的数据库连接。是否必须单独连接?

c - 如何让 gcc 将包含函数调用的表达式识别为常量?

c - 我使用 %c 错了吗?

计算 C 语言中的某个特定字母?

c - 我需要更改什么才能使这个 C 程序在 Linux 上运行?

c - 在 C 代码中从队列中读取给定元素

javascript - 从回调函数中获取值

python - 如何循环具有多个输入的函数?