在C中检索数组的用户输入

时间:2017-10-23 16:11:48

标签: c arrays visual-studio

初学者编程包括数组,而我只是在获取数组的用户输入时遇到了麻烦。我所包含的printf函数只是检查我的数组是否正常工作,我编写的较大程序只需要使用这两个数组。

char数组的输入似乎工作正常,我尝试了几种不同的方法。但是,int数组似乎没有使用我在char数组中成功使用的相同方法。不知道我错过了什么。下面是我运行程序时的代码和输出:

int main()
{

char grades[5]; // create array to store letter grades
int hours[5]; // array to store hours

puts("Please enter letter grades:"); // Input letter grades using fgets
fgets(grades, 5, stdin);

printf("Letter grade for course 3 is %c.\n", grades[2]);


int x = 0;

puts("Please enter course hours:\n");
for (x = 0; x < 5; x++)
{
    scanf("%d", &hours[x]);
}

printf("Course hours for course 2 are: %d.\n", hours[1]);

return 0;
}

此代码的输出:

Please enter letter grades:
ABCDF <- user input
Letter grade for course 3 is C.
Please enter course hours:

Course hours for course 2 are: -858993460.
Press any key to continue . . .

1 个答案:

答案 0 :(得分:1)

fgets(grades, 5, stdin);捕获输入流中留下ABCD的输入Fscanf("%d", &hours[x]);虽然尝试了五次,却无法解析F中的int。每次失败都会在输入流中留下F 使缓冲区足够大,以便进行典型输入 对所有输入使用fgets。使用sscanf或其他人进行解析。使用sscanf的返回来确保解析成功。

#include <stdio.h>

int main( void)
{

    char grades[50] = ""; // create array to store letter grades
    char line[50] = "";
    int hours[5] =  { 0}; // array to store hours
    int result = 0;

    puts("Please enter letter grades:"); // Input letter grades using fgets
    fgets(grades, sizeof grades, stdin);

    printf("Letter grade for course 3 is %c.\n", grades[2]);


    int x = 0;

    for (x = 0; x < 5; x++)
    {
        do {
            printf("Please enter course %d hours:\n", x + 1);
            fgets ( line, sizeof line, stdin);
            result = sscanf( line, "%d", &hours[x]);
            if ( result == EOF) {
                printf ( "EOF\n");
                return 0;
            }
        } while ( result != 1);
    }

    printf("Course hours for course 2 are: %d.\n", hours[1]);

    return 0;
}