开发者

How do i ignore characters after a certain spot on each line in C?

I am trying to input txt files into my C program that look something like this

开发者_StackOverflow123 x 182   //this is a comment in the file
1234 c 1923  //this is another comment in the file
12 p 3      //this is another comment in the file

I need to store the int, the single character and the other int on each line and then I want to ignore everything else on the line. Here is what I tried....

while (fscanf(file, "%d %c %d", &one,&two,&three) !=EOF)
                {
                        printf("%d %c %d\n", one,two,three);
                }

Right now I'm just printing out the values to test the process. So, if I test this with a file that does not have any comments or extra stuff after the first 3 things I need, it works perfectly. But if there is extra stuff, I get stuck in an infinite loop where the first line is repeatedly printed.


There may be a better way in C, but you could add a loop inside of your current loop to read in the remaining characters until you hit a newline.

while (fscanf(file, "%d %c %d", &one,&two,&three) !=EOF)
{
     printf("%d %c %d\n", one,two,three);
     while(fgetc(file) != '\n'){};
}

This should break out of the nested while loop as soon as the character it gets is a newline, and the next fscanf will begin on the next line.


If you're libc supports POSIX 2008 (like at least glibc on linux does), you can use getline and sscanf:

int len;
char *line;
while (getline(&line, &len, file) != -1) {
    sscanf(line, "%d %c %d", &one, &two, &three);
    printf("%d %c %d\n", one,two,three);
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜