The problem: I am attempting to use scanf to read a sentence with fields seperate by | ,so naturally i use the scanf's natural features to ignore this symbol but it then also ignores everything that has a | in it.
The code, simplified:
int main(){
char* a=malloc(8);
char* b=malloc(8);
scanf("%s | %s",a,b);
printf("%s %s",a,b);
}
when i attempt the input:
TEST | ME
it works as intended, but when i have the following case:
TEST ME|
it naturally reads the test, but ignores the ME|, is there any way around this?
Explanation: The %*s in scanf is used to ignore some input as required. In this case, it ignores the input until the next space or newline. Similarly, if you write %*d it will ignore integers until the next space or newline.
The secret to getting scanf to perform this way is to put a blank in the format string before the %c format specifier. The blank tells scanf to skip white space and it will actually skip any number of white space characters before reading and storing a character.
For a simple solution, you could add a space before the format specifier when you use scanf(), for example: scanf(" %c", &ch); The leading space tells scanf() to skip any whitespace characters (including newline) before reading the next character, resulting in the same behavior as with the other format specifiers.
We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note the extra space). We can add a getchar() after scanf() to read an extra newline.
scanf("%[^ \t|]%*[ \t|]%[^ \t\n|]", a,b);
printf("%s %s",a,b);
Annotation:
%*
: ignore this element.
E.g. %*s
//skip the reading of the text of this one
%[character set(allow)]
: Read only character set that you specify.
E.g. %[0123456789]
or %[0-9]
//Read as a string only numeric characters
%[^character set(denied)]
: It is to mean character other than when ^
is specified at the beginning of the character set.
Yes, you can scan for a character set. The problem you're seeing is not related to the vertical bar, it's the fact that a string stops at the first whitespace character, i.e. the space between "TEST"
and "ME|"
.
So, do something like:
if(scanf("%7[^|] | %7[^|]", a, b) == 2)
{
a[7] = b[7] = '\0';
printf("got '%s' and '%s'\n", a, b);
}
See the manual page for scanf()
for details on the [
conversion specifier.
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