I am try to read in some data with an id followed by firstname lastname from a text file and I cannot seem to get scanf to allow the space.
input may look like:
123456 FirstName LastName
scanf("%d%s", &id, fullName) doesn’t work because it cuts off at the space between first and last name. I would like to have ‘first last’ in one string (preferrably without concat because there are instances where the last name is not included).
You can use the set notation to specify a set of allowable characters in your name, and explicitly allow spaces:
Here,
[]specifies a set of characters to allow (see man 3 scanf), and within there there is a space,a-z, which means “all lower-case characters” andA-Zwhich means “all upper-case characters.All that said, you should specify a maximum width, to avoid overflowing your buffer. For example:
Note the use of 63 instead of 64; the man page notes that it will read in the number of characters specified, and then a NULL-terminator: