1
votes

Now i read somehwere:

The scanf() conversion %[\n] will match a newline character, while %[^\n] will match all characters up to a newline.

But in the following code:

#include<stdio.h>


int main() {
printf("Enter Something: ");
char name[100];   
scanf("%99[help]", name);
printf("%s",name);
}

I face no problem when i enter help me as the printed word is help. However when i enter I need help it prints garbage. Please help how to fix this problem? My target is to match the word help entered anywhere along the input, e.g.,

"This is a test, i need help in this"

Should detect help.

2
That you can write %[\n] doesn't automatically mean you can write %[help]. You're leaping to conclusions and making assumptions: not good in programming! (I'm not even convinced that it's valid for \n.) What are you actually trying to achieve here?Lightness Races in Orbit
I am talking about pattern matching.Sadique
@NabinSur: What are you actually trying to achieve here?Lightness Races in Orbit

2 Answers

2
votes

You need to check the result of scanf. If it fails to match, the pointer you pass in is not modified. In your specific case, name would then contain arbitrary data.

Once you check the output of scanf, you'll see it's failing to match on that string. scanf is not a regular expression parser. It will only attempt a match on the first "item" it sees on the input stream.

The match specifier %99[help] means "i want to match anything that contains the letters h, e, l, p in any order, up to 99 chars long". That's all. So it fails on the very first letter of your input ("T"), which is not in the set.

If you want to look for a string inside another string, use strstr for example. To read a whole line, if your environment has it, the easiest is to use getline.

1
votes

You need the scanset to recognize all the characters you might enter. You also need to check the return from scanf() to see whether it succeeded.

#include <stdio.h>

int main()
{
    printf("Enter Something: ");
    char name[100];   
    if (scanf("%99[Indhelp ]", name) != 1)
        fprintf(stderr, "scanf() failed\n");
    else
        printf("%s",name);
    return 0;
}

That will recognize "I need help" and many other phrases. The C standard says:

If a - character is in the scanlist and is not the first, nor the second where the first character is a ^, nor the last character, the behavior is implementation-defined.

In many implementations, you can use a notation such as %[a-zA-Z ] to pick up a string of letters or spaces. However, that is implementation-defined behaviour. That means it could do anything the implementation chooses, but the implementation must document what it does mean.

The reliable way to write the scanset is:

%[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ]

Of course, that leaves you with some issues around punctuation, not to mention accented characters; you can add both to the scanset if you wish.