变量和scanf函数的问题

时间:2014-11-01 14:47:44

标签: c

我对c编程语言很陌生。我写了这段代码,我想知道是否有任何办法 写这段代码更短更有效?

代码:

#include <stdio.h>

int main(){

    printf("This is my first program.\nPlease put in your name...\n");

    char letter[5];


    scanf("%c%c%c%c%c%c", &letter[0], &letter[1], &letter[2], &letter[3], &letter[4], &letter[5]);


    if(letter[0] == 't' && letter[1] == 'r' && letter[2] == 'a' && letter[3] == 'v' && letter[4] == 'i' && letter[5] == 's'){
        printf("Access Granted\nWelcome Travis.\n");
        return 0;
    }



    else{
        printf("You are not autorized.\nThis program will exit now...\n");
        getchar();

    }

    }if(letter[0] == 'b' && letter[1] == 'o' && letter[2] == 'b'){
        printf("Access Granted\nWelcome Bob.\n");
        return 0;
    }

2 个答案:

答案 0 :(得分:1)

scanf("%c%c%c%c%c%c", &letter[0], &letter[1], &letter[2], &letter[3], &letter[4], &letter[5]);

错误,因为letter长度为5个元素,索引为0-4。因此,在scanf上方,letter[5]不是有效位置。你超出了数组的范围。要修复它,只需声明大小为7的数组(6个字符为“travis”+1,最后为\0)而不是5:

char letter[7];

然后,可以使用scanf缩短%s

scanf("%6s",letter);

接下来,

if(letter[0] == 't' && letter[1] == 'r' && letter[2] == 'a' && letter[3] == 'v' && letter[4] == 'i' && letter[5] == 's')

if(letter[0] == 'b' && letter[1] == 'o' && letter[2] == 'b')

可以使用strcmp标头中的string.h函数进行缩短,并使用逻辑OR运算符进行合并:

if(strcmp(letter,"bob")== 0 || strcmp(letter,"travis") == 0)
{...}

全部放在一起,

#include <stdio.h>
#include <string.h>

int main(){

    printf("This is my first program.\nPlease put in your name...\n");

    char letter[7];


    scanf("%6s", letter);


    if(strcmp(letter,"bob")== 0 || strcmp(letter,"travis") == 0)
        printf("Access Granted\nWelcome %s.\n",letter);
    else
        printf("You are not autorized.\nThis program will exit now...\n");

    getchar();
    return 0; //you don't need these in every if and else.
    }

答案 1 :(得分:0)

你去吧

    #include <stdio.h>
    #include <stdlib.h>

    int main()
    {
       unsigned int len_max = 128;
       unsigned int current_size = 0;

       char *pStr = malloc(len_max);
       current_size = len_max;

       printf("\nEnter your string value:\n");

      if(pStr != NULL)
      {
        int c = EOF;
        unsigned int i =0;
        //accept user input until hit enter or end of file
        while (( c = getchar() ) != '\n' && c != EOF)
       {
          pStr[i++]=(char)c;

          //if i reached maximize size then realloc size
         if(i == current_size)
         {
            current_size = i+len_max;
            pStr = realloc(pStr, current_size);
         }
      }

      pStr[i] = '\0';

      printf("\nLong String value:%s \n\n",pStr);
      //compare pStr with your defined string for authentication.
      //e.g if(pStr=="myString"){printf("Access granted!");}
      //free memory 
      free(pStr);
      pStr = NULL;


      }
   return 0;
 }