简体   繁体   中英

reading a .txt file, C

I am trying to parse through a line a line of text from a .txt file and set it to a string. It is parsing most of the lines, except for the first 4 characters. This is what I'm trying to parse:

12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,2

And this is my code:

FILE * rooms;
int i;
char c;
char roomString[ROOM_STRING_LENGTH];    
rooms = fopen("assets/rooms.txt", "r");

if(rooms == NULL)
{
    printf("error opening file\n");
}

fscanf(rooms, "%s", roomString);
while((c=fgetc(rooms))!='\n')
{           
    roomString[i] = c;
    i++;
}
printf("%s\n", roomString);

Your fscanf() call consumes the first word of the input. Remove that call.

if(rooms == NULL)
{
    printf("error opening file\n");
}

//fscanf(rooms, "%s", roomString);
while((c=fgetc(rooms))!='\n')

Why do you do fscanf when you are doing fgetc. This fscanf increments the file pointer to the next word. Remove the fscanf and execute your code with the mentioned changes.

   #include<stdio.h>

   #define ROOM_STRING_LENGTH 50
    void main(){

    FILE* rooms;
    int i =0;
     char c;
     char roomString[ROOM_STRING_LENGTH];    
     rooms = fopen("rooms.txt", "r");
     if(rooms == NULL)
     {
        printf("error opening file\n");
      }

     //fscanf(rooms, "%s", roomString);
      //printf("%s\n", roomString);
     while((c=fgetc(rooms))!='\n')
     {

        roomString[i] = c;
         i++;
     }
     roomString[i] ='\0';
     printf("%s\n", roomString);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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