繁体   English   中英

我是C编程的新手,并且不断遇到分段错误

[英]I am completely new to C programming and keep getting a segmentation fault

这是一个酒店预订系统,它采用.txt文件,其中包含int string string int的行,然后将其读取并放入类型为room的数组中...同时扫描它一直给我分段错误...这是对于类,我不想要一个准备好的代码,但我只是不知道为什么我一直在分割......:/

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



typedef struct{
    int num; 
    char first[100];
    char last[100]; 
    int type;
    }room;

int main (int argc, char ** argv){

    FILE * myFile;

    if(argc !=2)
        {
                fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
                return EXIT_FAILURE;
        }

        myFile = fopen(argv[1],"r");

        if (myFile==NULL){

            fprintf(stderr, "no open!!\n");
            return EXIT_FAILURE;

        }


        // counter to add elements to my array
        int i = 0;

        char c;
        //array of room with the 150 rooms in it...
        room * rooms = malloc(150 * sizeof(room));

        while ((c = getc(myFile)) != EOF ){

            fscanf(myFile, "%d", rooms[i].num);
            printf("the room num is: %d", rooms[i].num);
            fscanf(myFile, "%s", rooms[i].first);
            fscanf(myFile, "%s", rooms[i].last);
            fscanf(myFile, "%d", rooms[i].type);
            i++;

        }
        fclose(myFile);


}

这是我在我的代码中修复并工作但它实际上是跳过它从...读取的.txt文件中的第一个整数...当它应该是1时它只读零,所以我注意到“(c = getc(myFile))!= EOF“是我的问题,它正在跳过它应该读取的第一个整数:/

while ((c = getc(myFile)) != EOF ){


            fscanf(myFile, "%d", &rooms[i].num);
            fscanf(myFile, "%s", rooms[i].first);
            fscanf(myFile, "%s", rooms[i].last);
            fscanf(myFile, "%d", &rooms[i].type);

            printf("the room num is: %d and is occupied by %s %s and it is a                                      %d\n", rooms[i].num, rooms[i].first, rooms[i].last, rooms[i].type);
            i++;

        }

.txt文件的第一行如下:1 carri alston 0

在你的代码中

fscanf(myFile, "%d", rooms[i].num);

应该

fscanf(myFile, "%d", &rooms[i].num);

type东西相同。

除此之外,您应该始终检查fscanf()的返回值以确保正确scan

另外,你需要检查i的值,以便它不应该访问超出范围的内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM