简体   繁体   中英

Input filtering using scanf

I want to filter input. I don't know what is the best way. I want words starting with alpha-bates to be read. For example, if the input is:

This is 1 EXAMPLE1 input.

The string should be like this:

This is  EXAMPLE1 input

What is the easiest way to filter input like this?

I tried using "%[a-zA-Z]s" , but it not working.

Your scan string "%[a-zA-Z]s" probably isn't want you think it is. Drop that trailing s .

"%[a-zA-Z]" will scan a string consisting entirely of lower and uppercase letters. So numbers will be discounted. However, you want to scan alpha-numeric strings that begin with a lower or uppercase letter. scanf doesn't provide a facility to look for a string in that way. You can, instead, scan for an alpha-numeric string with "%[a-zA-Z0-9]" , and then drop the scanned input if it the first character of the string is numeric.

Using scanf is tricky for various reasons. The string may be longer than you expect, and cause buffer overflow. If the input isn't in the format you expect, then scanf may fail to advance past the unexpected input. It is usually more reliable to read the input into a buffer unconditionally, and parse the buffer. For example:

const char *wants
    = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
std::string word;
while (std::cin >> word) {
    if (!isalpha(word[0])) continue;
    std::string::size_type p = word.find_first_not_of(wants);
    word = word.substr(0, p);
    //... do something with word
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM