简体   繁体   中英

fscanf () read error

I have a text file which I'm reading in first and last names into a character array of size 20. I'm creating a struct array which holds the "People's" information. The text file looks as follows:

John Robbins
Teresa Jones 

my struct is defined as such:

struct people {

char name[20];
};

Declaration of Persons struct:

 struct people *persons[2];

After declaring a new struct I read in the names with the following code:

for(i=0; i<2; i++)
{  
  fscanf(dp, "%[^\n]s", &persons[i].name[20]);
}

However, once I output the names to the console I receive the following:

hn Robbins
sa Jones

I've done extensive research and cannot find the solution to this problem. Has anyone experienced this problem?

fscanf(dp, "%[^\n]s", &persons[i].name[20]);

This reads the line up to a newline, and then attempts to read an s which will fail. The line up to the newline will be stored after the end of the name array in your people struct (which means it will overwrite into the next element of the persons array.

You want something like:

fscanf(dp, " %19[^\n]%*[^\n]", persons[i].name);

instead -- the initial space skips leading whitespace (including any newline from a previous line.) The %19[^\\n] reads up to 19 characters or up to a newline and stores it, followed by a terminating NULL (so will use up the entire 20 byte name array, but no more). The %*[^\\n] will read any additional characters on the line up to (and not including) the newline and throw them away.

You also want to check the return value of the fscanf call to make sure it doesn't get an error or end of file:

#define MAX_PEOPLE    2
struct people persons[MAX_PEOPLE];

i = 0;
while (i < MAX_PEOPLE && fscanf(dp, " %19[^\n]%*[^\n]", persons[i].name) > 0)
    i++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM