使用指针和数组创建随机故事生成器来处理字符串

时间:2014-10-22 18:55:53

标签: c arrays pointers c-strings srand

我想弄清楚我应该如何构建我的下一个编程类实验室。这是我到目前为止所拥有的。问题逐行:

int main()
{       
    char name, color, person; //color, pet and car are the only arrays. The rest will be read in
    int age;

    const char* pet[5]={"dog", "cat", "bird", "snake", "monkey"}; //not sure how to set up these pointers...
    const char* car[5]={"porsche 911", "honda prelude", "toyota prius", "shelby mustang"};

    printf("What is your name?   \n");
    scanf("%c", &name);
    printf("How old are you?  \n");
    scanf("%d", &age);
    printf("What is your favorite color?  \n");
    scanf("%c", &color);
    printf("What is the name of your best friend?  \n");
    scanf("%c", &person);


    printf("%c is an awesome person.\n", name);
    printf(" They are currently %d years old and drive a %c %s.\n", age, color, car[5]); // trying to reference array in text
    printf(" %c 's best friend, %c, picks them up in a %s and drives them over to see their pet %s", name, person, car[5], pet[5]); // trying to reference array in text

    pet[5]=srand(time(NULL));// Where should this go? do I need one to reference each array?
    car[5]=srand(time(NULL));

    system("Pause");
    return 0;
}

更新于4月17日10月22日。我现在收到的唯一编译错误是将数组与srand函数相关联

1 个答案:

答案 0 :(得分:0)

有很多问题。

  • namecolorperson应该是char数组,而不是char
  • car[5]pet[5]的索引超出范围
  • pet[5]=srand(time(NULL));我不知道你想用这个来实现什么。它没有任何感觉。你应该更新你的问题并详细说明。

目前已更正的代码:

int main()
{       
    char name[50], color[50], person[50]; //color, pet and car are the only arrays. The rest will be read in
    int age;

    const char* pet[5]={"dog", "cat", "bird", "snake", "monkey"}; //not sure how to set up these pointers...
    const char* car[5]={"porsche 911", "honda prelude", "toyota prius", "shelby mustang"};

    printf("What is your name?   \n");
    scanf("%s", name);
    printf("How old are you?  \n");
    scanf("%d", &age);
    printf("What is your favorite color?  \n");
    scanf("%s", color);
    printf("What is the name of your best friend?  \n");
    scanf("%s", person);

    printf("%s is an awesome person.\n", name);
    printf(" They are currently %d years old and drive a %s %s.\n", age, color, car[4]); // trying to reference array in text
    printf(" %s 's best friend, %s, picks them up in a %s and drives them over to see their pet %s", name, person, car[3], pet[4]); // trying to reference array in text

    //no clue what this should be
    //pet[5]=srand(time(NULL));// Where should this go? do I need one to reference each array?
    //car[5]=srand(time(NULL));

    system("Pause");
    return 0;
}