Reading line by line using fscanf

家住魔仙堡 提交于 2020-05-16 04:58:07

问题


I want to read a file with 3 lines:

The first one with strings, second with a number and the third with strings again.

Example:

Line 1: bird toy book computer water

Line 2: 2

Line 3: toy water

I have this code, that reads a file, word by word storing them in the word array, and then putting the word into the words 2d array.

char words [5][50];
char word [50];
int i,j;
j = 0;

while( (fscanf(file, "%s", word))!=EOF ){
    for(i = 0; i<50; i++){
        if(word[i] != NULL){
            words[j][i] = word[i];
        } else{
            break;
        }
    }
    j++;

}

it's working, but it reads all the lines, i want a way to just do this process for the first line, and then store the second line into a int variable and the third line into another 2d array.


回答1:


Read more about fscanf. It is not suitable to read line by line.

Consider instead reading every line with fgets or even better (on POSIX) with getline (see this), then parse each line perhaps with sscanf. Its return value (the count of scanned items given from sscanf etc...) could be useful to test (and you might also want to use %n in the scan control format string; as Jonathan Leffler commented, read also about %ms assignment-allocation modifier, at least on POSIX systems, see Linux sscanf(3)).

BTW, hard-coding limits like 50 for your word length is bad taste (and not robust). Consider perhaps using more systematically C dynamic memory allocation (using malloc, free and friends) and pointers, perhaps using sometimes flexible array members in some of your struct-s



来源:https://stackoverflow.com/questions/44862582/reading-line-by-line-using-fscanf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!