Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf without additional arguments in C

Tags:

c

scanf

Is it allowed to use scanf(" ") without additional arguments to ignore initial whitespaces?
I'm using getchar() to read the chars of a word, and I want to ignore the whitespaces before the word (whitespaces after are used to check the end of the word).
The code is the following, is it correct?

char *read_word() {
    int size = 2;
    int char_count = 0;
    char *s;
    char ch;

    s = mem_alloc(size);

    scanf(" ");

    while ((ch = getchar()) != EOF) {
        if (char_count >= size) {
            s = mem_realloc(s, size++);
        }

        if (ch == ' ' || ch == '\n') {
            s[char_count] = '\0';
            break;
        }

        s[char_count++] = ch;
    }

    return s;
}
like image 512
raxell Avatar asked Feb 11 '16 17:02

raxell


People also ask

How do I ignore input in scanf?

Inserting an asterisk between % and any specifier tells scanf to ignore that entry: scanf(“%*s, %lf”,&radius);

How many arguments can scanf have in C?

In this case, scanf() has always exactly two arguments. The way to determine how many arguments a function is receiving is to look at your code and search with your eyeballs for the function call in question.

Does scanf skip whitespace?

This happens because scanf skips over white space when it reads numeric data such as the integers we are requesting here. White space characters are those characters that affect the spacing and format of characters on the screen, without printing anything visible.

What can I use instead of scanf in C?

To convert the input, there are a variety of functions that you can use: strtoll , to convert a string into an integer. strtof / d / ld , to convert a string into a floating-point number. sscanf , which is not as bad as simply using scanf , although it does have most of the downfalls mentioned below.


2 Answers

From the definition of the scanf() function (*), emphasis mine:

The format is composed of zero or more directives: one or more white-space characters, an ordinary multibyte character (neither % nor a white-space character), or a conversion specification.

[...]

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

So scanf( " " ); is perfectly valid.


(*): ISO/IEC 9899:1999, 7.19.6.2 The fscanf function, section 3 and 5.

The other *scanf functions are defined in terms of this section.

like image 150
DevSolar Avatar answered Sep 17 '22 23:09

DevSolar


To add to the other answers, all of the following are valid:

scanf(" ");      // skip over whitespace
scanf("xyz");    // skip over the longest leading substring of "xyz" if present
                 // i.e. "xyz" or "xy" or "x"
scanf(" %*s ");  // skip over the first string and whitespace around it
like image 36
dxiv Avatar answered Sep 16 '22 23:09

dxiv