#include /* * To read strings you have essentially 2 templates: * * - %s: the string is considered to be over whenever * a whitespace is encountered. * * - %[...] you can specify what characters make up your string. * * In the specification, '-' stands for a range of characters, * unless it is the first or the last character, in which case * it stands for itself. * * E.g. %[0-9a-zA-Z] matches a string made of digits, * lower case and upper case letters. * %[a-z-] matches a string made of lower case letters * and hyphens (-). * %[-0-9_ a-z] matches a string made of digits, hyphens, * spaces and lower case letters. * * (see the libc manual for a full explaination, the %[ template * is very flexible and handy). */ /* * Whenever you read a string you have to _preallocate_ a buffer of the * proper size. That is, if you want to read a string that is long AT * MOST 100 characters, you have to initialize a buffer of size 101 and * pass it as the argument of the %s or %[ template. * * E.g: * * char string[101]; * ... * scanf("%[ a-b0-9]", string); */ /* * PROBLEM: the string that you read might be larger than the buffer, * causing various problems (buffer overflows, segmentation faults...). * * SOLUTION: you can tell your templates that your string has a maximum * length. Actually, you ****** M U S T ****** do it. (if you didn't * notice, it is important). * * You can do it by putting the maximum length to match between the '%' * and the 's' or '[' in the template definition. * * E.g.: * * char buffer[55]; * .... * scanf("%54s", buffer); * ... * scanf("%54[a-z0-9_]", buffer); * * SPECIFING THE MAXIMUM DIMENSION OF THE ACCEPTING BUFFER IS THE PROPER * AND SAFE WAY TO READ STRINGS IN C. */ /* * If the string is longer, then the remaining characters are left to * be consumed by the next call to scanf. */ int main(void) { char longbuffer[21]; // A proper way to handle input strings printf("Inserisci una stringa (cifre, lettere non accentate e spazi).\n"); scanf("%20[a-zA-Z0-9 ]", longbuffer); printf(" ==> Ho letto: %s\n", longbuffer); return(0); }