Skip to main content
GameDev.net gamedev.net
🔒 Locked

[Solved] fscanf() is not skipping whitespace

Started by Gage64 Sep 7, 2008 at 10:58 AM 2 replies 1.6k views
Original Post
Gage64
Gage64
According to what we studied in class and the documentation we were given, fscanf() should skip whitespace, but it's not doing it in my program. I tried testing it in a small separate program:
void main() {
    char ch;
    FILE *file;

    file = fopen("d:/a.txt", "r");
    fscanf(file, "%c", &ch);
    fscanf(file, "%c", &ch);
    fclose(file);
}

a.txt contains only two characters, a space and 'g'. I would expect that after the first call to fscanf(), ch would contain 'g', but instead it contains the space. After the second call, it contains 'g'. What am I missing? Thanks in advance. [Edited by - Gage64 on September 7, 2008 11:20:42 AM]
swiftcoder
swiftcoder
Quote:
Original post by Gage64
According to what we studied in class and the documentation we were given, fscanf() should skip whitespace, but it's not doing it in my program.
From the man page for scanf:
Quote:
%c: Matches a sequence of width count characters (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating NUL is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.
Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]
Gage64
Gage64
That worked, and thank you very much.

The part you quoted doesn't appear in my documentation, so I googled for "scanf man page" (because it appeared in your post) and the documentation I found seems much more comprehensive than what I have. This will certainly be useful in the future.

Thanks again.

swiftcoder
swiftcoder
Quote:
Original post by Gage64
The part you quoted doesn't appear in my documentation, so I googled for "scanf man page" (because it appeared in your post) and the documentation I found seems much more comprehensive than what I have.
The unix manpages tend to be pretty close to the definitive documentation for POSIX and stdc functions :)
Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.