Ignoring separating character using scanf

33,019

Solution 1

    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.

Solution 2

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.

Solution 3

This one should work.

char a[200], b[200];

scanf ("%[^|]| %[^\n]", a, b);  // Use it exactly
printf ("a = %s\nb = %s\n", a, b);

Meaning of this formatting. I seperate the format string into 3 parts and explain.

"%[^|]" - Scan everything into 1st string, until the bar character('|') appears.

"| " - Read the '|' and ignore it. Read all white space characters and ignore them.

"%[\n]" - Read remainder of the line into the 2nd string.

Test case

first string is         this | 2nd is this
a = first string is     this
b = 2nd is this

no space|between bar
a = no space
b = between bar
Share:
33,019
Thongurf
Author by

Thongurf

Updated on July 24, 2022

Comments

  • Thongurf
    Thongurf almost 2 years

    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?