Reputation: 31
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
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
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