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;
}
Inserting an asterisk between % and any specifier tells scanf to ignore that entry: scanf(“%*s, %lf”,&radius);
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With