C/Console/Console Read Validation

Материал из C\C++ эксперт
Версия от 13:22, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Characters in the format control string

<source lang="cpp">

  1. include <stdio.h>

void main() {

  int i = 10;
  int j = 10;
  int k = 10;
  float fp1 = 10.0;
  k = scanf("fp1 = %f i = %d %d", &fp1, &i , &j);
  printf("\nCount of values read = %d", k);
  printf("\nfp1 = %f\ti = %d\tj = %d\n", fp1, i, j);

}


      </source>


Exercising formatted input

<source lang="cpp">

  1. include <stdio.h>

void main() {

  int i = 10;
  int j = 10;
  int k = 10;
  float fp1 = 10.0;
  char word1[20] = " ";
  char word2[20] = " ";
  k = scanf("%f %d %d %[abcdefghijklmnopqrstuvwxyz] %*1d %s",
    &fp1, &i , &j, word1, word2);
  printf("\nCount of values read = %d\n", k);
  printf("\nfp1 = %f   i = %d   j = %d", fp1, i, j);
  printf("\nword1 = %s   word2 = %s\n", word1, word2);

}


      </source>


Narrow down the input by setting scanf

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 char str[80];
 printf("Enter letters, anything else to stop\n");
 scanf("%[a-zA-Z]", str);
 printf(str);
 return 0;

}


      </source>


Narrow the input: letter and space

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 char str[80];
 printf("Enter letters and spaces\n");
 scanf("%[a-zA-Z ]", str);
 printf(str);
 return 0;

}


      </source>


Read a certain length of string

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 int i;
 char str[80], str2[80];
 scanf("%20s", str);
 printf("%s",  str );
 return 0;

}

      </source>


Reading monetary amounts separated by commas and spaces

<source lang="cpp"> /*

 Ensure that the input format string specifies that "$",
 spaces, and commas are ignored.
  • /
  1. include <stdio.h>

void main() {

 double amounts[4] = {0.0};
 double total = 0.0;
 int i = 0;
  printf("Enter the four amounts:\n");
  for(i = 0 ; i<4 ; i++)
  {
    scanf("%*[ ,$]%lf", &amounts[i]);
    total += amounts[i];
  }
    
  printf("The total of the input is: $%.2lf\n", total);

}


      </source>


Reading types of strings from the keyboard

<source lang="cpp"> /* Beginning C, Third Edition

By Ivor Horton
ISBN: 1-59059-253-0
Published: Apr 2004
Publisher: apress
  • /

/* type 1: a sequence of lowercase letters followed by a digit. e.g. number1 type 2: two words that both begin with a capital letter and have a hyphen between them. e.g. Seven-Up type 3: a decimal value. e.g. 7.35 type 4: a sequence of upper or lower case letters and spaces. e.g. Oliver Hardy type 5: a sequence of any characters except spaces and digits that does not

       start with a letter. e.g. floating-point

The simple approach is to use the fact that each string after the first starts with a character that does not appear in the previous string. Thus you can specify the characters for each string as anything that is not the first character in the string that follows. This approach would allow illegal characters in the string to be read. e.g. the first string could be read as any lowercase letter or digit. To positively ensure the strings are in the form specified is much more work as the code here shows. If you wanted to allow erroneous data to be re-entered, it would be easiest if you require each input to be on a separate line.

  • /
  1. include <stdio.h>
  2. include <stdlib.h>
  3. include <string.h>

void main() {

  char word1[50];
  char word2[50];
  char word3[50];
  char word4[50];
  char word5[50];
  char temp[50];
  int k = 0;
  printf("Enter the five strings:\n");
  /* Read first string, first the lowercase letters, then the digit */
  k = scanf(" %[abcdefghijklmnopqrstuvwxyz]%1[0123456789]", word1, temp);
  if(k<2)
  {
    printf("Incorrect input for first string - program terminated.\n");
    exit(1);
  }
  strcat(word1,temp);
  /* Read second string, first the uppercase letter, then the following
     letters, then the hyphen, then the uppercase letter, finally the
     following letters.                                                
  */
  k = scanf(" %1[ABCDEFGHIJKLMNOPQRSTUVWXYZ]", word2);
  if(k<1)
  {
    printf("Incorrect input for second string - program terminated.\n");
    exit(1);
  }
  scanf("%[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]", temp);
  strcat(word2,temp);
  k = scanf("%1[-]", temp);
  if(k<1)
  {
    printf("Incorrect input for second string - program terminated.\n");
    exit(1);
  }
  k = scanf(" %1[ABCDEFGHIJKLMNOPQRSTUVWXYZ]", temp);
  if(k<1)
  {
    printf("Incorrect input for second string - program terminated.\n");
    exit(1);
  }
  strcat(word2,temp);
  scanf("%[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]", temp);
  strcat(word2,temp);
  /* Read the third string. I cheat a bit because I read this assuming it is a well-formed
     decimal string. To verify that is really is, you could read it as a decimal
     value and then convert it to a string.
  */
  k = scanf(" %[0123456789.-]", word3);
  if(k<1)
  {
    printf("Incorrect input for third string - program terminated.\n");
    exit(1);
  }
  /* Read the fourth string. */
  scanf("%[ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]", word4);
  if(k<1)
  {
    printf("Incorrect input for fourth string - program terminated.\n");
    exit(1);
  }
  /* Read the fifth string. You must exclude newline, otherwise it will be
     rad as part of the string.
  */
  scanf(" %[^ 0123456789\n]", word5);
  printf("The input strings read are: \n%s  %s  %s  %s  %s\n",
           word1, word2, word3, word4, word5);

}


      </source>


Read only a range of char

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 int i;
 char str[80], str2[80];
 scanf("%d%[abcdefg]%s", &i, str, str2);
 printf("%d %s %s", i, str, str2);
 return 0;

}


      </source>