1
votes

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).

3

3 Answers

5
votes

You can use the set notation to specify a set of allowable characters in your name, and explicitly allow spaces:

scanf("%d %[ a-zA-Z]", &id, fullName);

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" and A-Z which means "all upper-case characters.

All that said, you should specify a maximum width, to avoid overflowing your buffer. For example:

char fullName[64]; // allocate 64-byte array and set to 0
scanf("%d %63[ a-zA-Z]", &id, fullName);

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:

String input conversions store a null terminator ('\0') to mark the end of the input; the maximum field width does not include this terminator.

3
votes

scanf doesnt allow spaces in it you can use gets() or preferably fgets() function. gets copies whole line into the string while fgets copies the number of character specified

if you want to do it with scanf use %[^\n] instead of %s

1
votes

There are a couple of ways you can do this:

  • To read in characters up until the end of the line, you can replace the format specifier %s with one like %[^\n], which simply means read up until a \n is encountered.

  • An alternative is to use use fgets() to read the string after you've read your int. This has the added benefit of preventing buffer overflows, as you have to pass to fgets() the maximum amount of characters to be read.