如何验证结构成员?

时间:2015-05-21 11:20:40

标签: c validation structure scanf

我需要验证bookid结构成员。此代码与库管理代码有关....我需要验证从用户获取的所有输入。应包括作者姓名,书籍详细等所有输入。

struct 
{
  int bid;
  char bname[25] ;
  char author[25];
  int nooftitles;
  char titles[500];
  int status;
}book;

void Addbook()
{
    int i;book.status=IN;
            //opening the librecord file
    librecord = fopen("librecord.txt","a+");
//need to validate below member
    printf("Enter The uniqueid of The Book :(Integer) \n");
        scanf("%d",&book.bid);



printf("Enter The Name of The Book :\n");
        scanf("%s",book.bname);
    printf("Enter The Name of Author :\n");
        scanf("%s",book.author);
    printf("Enter The Number of Titles Of The Book:(Integer)\n");
        scanf("%d",&book.nooftitles);
    fprintf(librecord,"\n%d\t%s\t%s\t%d\t%d\t",book.bid,book.bname,book.author,book.status,book.nooftitles);
    printf("Enter The Titles Of The Book : \n");
    for(i=0;i<book.nooftitles;i++)
    {
        scanf("%s",book.titles);
        fprintf(librecord,"%s\t",book.titles); 
    }
    fclose(librecord);
    printf(" (' ' ) A New Book has been Added Successfully...\n");

}

1 个答案:

答案 0 :(得分:1)

要验证输入主要是),您需要处理两件大事,

  1. 检查scanf()的返回值是否与所谓扫描的确切项目数相匹配。

    示例:

     if ( scanf("%d",&book.bid) != 1)
     {
        //error handling
     }  
    
  2. 将长度修饰符与%s一起使用,以避免缓冲区溢出的可能性。

    示例:对于

    char bname[25] ;
    

    使用

    scanf("%24s",book.bname);
    
  3. 如上所述, M Oehm的评论中提到,如果您想要空格分隔的单词作为输入,%s将无效。然后,您需要使用fgets()来读取和存储输入。