fscanf is a C function designed to read character by character from a file to the system
how we can use scanf programmatically to read till first white space ????

:) :)

Dani AI

Generated

A quick clarification that helps this thread: if you want to capture the next word from a FILE *in until the first whitespace and store it safely, give %s a field width and check the return value. The delimiter remains unread in the stream, which is usually what you want for subsequent parsing.

char word[64];
if (fscanf(in, "%63s", word) == 1) {
    /* use word */
}

If the token might be very long or you need to handle cases where the first character could be whitespace (yielding an empty token), read a line and cut at the first whitespace yourself. This avoids buffer overflows and gives you full control over what counts as whitespace.

char buf[256];
if (fgets(buf, sizeof buf, in)) {
    size_t n = strcspn(buf, " \t\r\n\f\v");
    buf[n] = '\0';    /* buf now holds characters up to the first whitespace (possibly empty) */
    /* use buf */
}

Since @omar isaid ultimately switched to C++ streams, note that operator>> for std::string already reads up to the next whitespace and is bounds-safe. It is the simplest equivalent to the above.

std::string word;
if (in >> word) {
    // use word
}

Tip: always validate the result (the == 1 or the stream state) so you can detect EOF and malformed input deterministically.

Recommended Answers

All 5 Replies

If you don't expect the first character to actually be whitespace, you can use "%*s". Otherwise, because %s ignores leading whitespace, you would need to use an exclusion scanset of whitespace:

fscanf ( in, "%*[^ \n\t\r\f\v]" );

Thank you very much You are so cute helping me
I talke to Professor and he allowed to use C++ streams

>You are so cute helping me
...

>I talke to Professor and he allowed to use C++ streams
So are you asking how to do it in with iostreams or is the question moot now?

the question is moot now , thank you very mush for your care

If you don't expect the first character to actually be whitespace, you can use "%*s". Otherwise, because %s ignores leading whitespace, you would need to use an exclusion scanset of whitespace:

fscanf ( in, "%*[^ \n\t\r\f\v]" );

>You are so cute helping me
...

>I talke to Professor and he allowed to use C++ streams
So are you asking how to do it in with iostreams or is the question moot now?

the question is moot now , thank you very mush for your care

I used the streams of the C++ that is much easier
Thank you very much Narue

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.