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?

Recommended Answers

All 2 Replies

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

commented: Thanks +1

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.