user2421117
user2421117

Reputation: 31

Storing each line of a file in a C struct but ignore an part of the line after a //

I am writing a program in C that needs to store each line of a text file in an array of structs however it needs to ignore the line after a "//" sign (i.e. a comment). I have been able to get it to store each line using the following code but I cannot figure out how to ignore any part of a line that begins with a '//'. This is the part of the code that I have that will store each line of the text file as a separate index in the array of structs:

while(!feof(fp))
{
    fscanf(fp, "%127s", rName[i].name);
    i++;
}

This is the definition of my struct

typedef struct{
    char [128] name;
    int nameLength;
} stringStruct;

If the following text below was in my text file I basically want to store only the "KeepThis" text and not store the "//ignorethis" text. I also want to store each line at a different index of my array.

KeepThis//ignorethis
//ignorethis
KeepThis

Any help would be greatly appreciated.

Upvotes: 3

Views: 389

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

easy way: search "//" by strstr and replace '\0'

#include <stdio.h>
#include <string.h>

int main(void){
    char line[128] = "KeepThis//ignorethis";
    char *p;
    p = strstr(line, "//");
    if(p != NULL)//found "//"
        *p = '\0';
    printf("%s\n", line);//KeepThis
    return 0;
}

Upvotes: 1

Imre Kerr
Imre Kerr

Reputation: 2428

Add a null terminator where you find the //.

for (int i = 0; i < HOWEVERMANY; i++)
{
    for(int j = 0; j < 127 && rName[i].name[j] != '\0'; j++)
    {
        if (rName[i].name[j] == '/' && rName[i].name[j+1] == '/')
        {
            rName[i].name[j] = '\0';
            break;
        }
    }
}

Upvotes: 0

Related Questions