Reputation: 3
I have to write a code without third-party libraries that read from a file row by row and look for a switch or case operator. So far my code for that is this:
while(fgets(st, 1001, f1))
{
lineCnt++;
if(strstr(st, "switch"))
{
if(!strstr(st, "\""))
switchCnt++;
}
if(strstr(st, "case"))
{
if(!strstr(st, "\""))
caseCnt++;
}
}
Which basically looks if on a given line there's a quote and if there is, don't increase the switch count. I think this covers most of the cases since I don't think there's gonna be a quote on a row with an actual switch operator, but I'm open for ideas on that part as well. I've done the same for the case counter as well.
How to ignore the comment parts of the file reading, since if there's let's say //switch count
it's gonna be counted?
Upvotes: 0
Views: 123
Reputation: 31389
This is a trickier question to answer than you might think. The "proper" solution is to write a complete C parser, which is quite tricky.
In order to get it good, you need a better specification. But I think we can assume that you will not allow things like this:
#define switch haha
#define foobar case
And when it comes to comments. Remember that you have two types of comments. //
and /* */
. Furthermore, you also need to deal with string literals and multi character literals. Here is a snippet with some tricky quirks just to give an idea of what you're actually asking about:
/* switch program
int main(void)
// */
#include <stdio.h>
int main(void) {
char *str = "switch\" // /*";
/* char *str = "*/"switch";
printf("//");
switch((long)"case") /* { */ { /*
case 1 :
*/ case 1 : break;
}
int c = '"//"'; // Multi character constant which is including
// Both comment and quote character
// This is a comment \
and so is this
}
Note that the code above does not make sense, but it does compile.
Upvotes: 1
Reputation: 75062
To cut comments, cut comments.
If you simply want to cut all things after //
, it will be:
while(fgets(st, 1001, f1))
{
char* comment = strstr(st, "//");
if (comment != NULL) *comment = '\0';
Note that this cut will also applied to, for example, "hoge///";switch
.
(I don't know the syntax of the file to be deal with, so I cannot tell if this behavior is OK or not)
Upvotes: 0