使用strcpy在第二遍进行的不必要的输出

时间:2018-11-27 16:26:02

标签: c

我正在读一本书,名为“ C编程绝对入门指南”。 以下程序使用一些if循环和strcpy来存储用户提供的某些字符数组。 strcpy的第一遍工作正常。第二个产生垃圾。我知道数组需要\ 0结束。根据这本书,strcpy自动执行此操作。我想念什么?

#include <stdio.h>
#include <string.h>    
main()
{
    int ctr, numMovies, rating, favRating, leastRating;
    char movieName[40], favorite[40], least[40];

    favRating = 0;
    leastRating = 0;

    do {
    printf("How many movies have you seen this year? ");
    scanf(" %d", &numMovies);

    if (numMovies < 1)
    {
        printf("No movies! How can you rank them?\nTry again\n\n");
    }

    } while (numMovies < 1 );

    for (ctr = 1; ctr <= numMovies; ctr++)
    {

    printf("\nWhat's the name of the movie? ");
    printf("(1-word titles only!) ");
    scanf(" %s", movieName);


    printf("On a scale of 1 to 10, what would ");
    printf("you rate it? ");
    scanf(" %d", &rating);

    if (rating > favRating)
    {

        strcpy(favorite, movieName);

        favRating = rating;
    }

            printf("%s", movieName);
    if (rating < leastRating)
    { 

        strcpy(least, movieName);
        leastRating = rating;
    }

}
printf("\nYour Favorite Movie was %s.\n", favorite);
printf("\nYour Least-favorite movie was %s.\n", least);
return 0;

}

1 个答案:

答案 0 :(得分:1)

因为您将leastRating初始化为零,否则除非您的评分为负,否则您将不会受到最爱。不确定那是您想要的。

最好的建议是@xing,添加一个包含

#include <limits.h>

像这样初始化你的最佳和最差情况;

favRating = INT_MIN;
leastRating = INT_MAX;