简体   繁体   English

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

[英]Retrieving User Input for Arrays in C

Beginner programming including arrays and I'm having trouble just getting user input for the arrays.包括数组在内的初学者编程,我在获取数组的用户输入时遇到了麻烦。 The printf functions I've included are just to check whether my arrays are working, the larger program I'm writing just needs to use these two arrays.我包含的 printf 函数只是为了检查我的数组是否正常工作,我正在编写的更大的程序只需要使用这两个数组。

The input for the char array seems to work fine, I've tried a couple of different methods. char 数组的输入似乎工作正常,我尝试了几种不同的方法。 However, the int array doesn't seem to work using the same diversity of methods I've used successfully with the char array.但是, int 数组似乎无法使用我成功使用 char 数组的相同方法的多样性。 Not sure what I'm missing.不知道我错过了什么。 Below is the code and the output when I run the program:下面是我运行程序时的代码和输出:

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;
}

Output of this code:此代码的输出:

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 . . .

fgets(grades, 5, stdin); captures ABCD of the input leaving F in the input stream.捕获在输入流中离开F的输入的ABCD scanf("%d", &hours[x]); can't parse an int from F though it tries five times.尽管尝试了五次,但无法从F解析 int。 Each failure leaves the F in the input stream.每个失败都会在输入流中留下F
Make buffers large enough for typical input.为典型输入制作足够大的缓冲区。
Use fgets for all input.对所有输入使用fgets Parse with sscanf or others.sscanf或其他人解析。 Use the return of sscanf to make sure the parsing was successful.使用 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM