I am doing some self-made exercises lately to practice my C skills.

One of them is something like this:

Given a file with something like: "Peter Wilson the swordsman".
I want to store "Peter Wilson" in the char array "name" and "swordsman" in char array "title".

So far I've tried this:

char name[100];
	fscanf(file," %s",name);
	
	char title[100];
	fscanf(file," the %s\n",title);

	printf("%s the %s",name,title);

The result is that it scans "Peter" into "name" and the rest is all garbled text. Is there anyway to make %s ignore whitespace?

>Is there anyway to make %s ignore whitespace?
No, but you can use a scanset to get a little more control. For example, to read an entire line with fscanf you could do this:

char buffer[100];

fscanf ( file, "%99[^\n]", buffer );

However, in your case, selecting which strings go where is a little more complicated. You'd be better off reading an entire line and then parsing it with custom logic.

Comments
Thanks

>Is there anyway to make %s ignore whitespace?
No, but you can use a scanset to get a little more control. For example, to read an entire line with fscanf you could do this:

char buffer[100];

fscanf ( file, "%99[^\n]", buffer );

However, in your case, selecting which strings go where is a little more complicated. You'd be better off reading an entire line and then parsing it with custom logic.

Thanks a lot :)

This question has already been answered. Start a new discussion instead.