Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 在结构数组中输入字符的循环无法正常工作_C_Arrays_Loops_Structure - Fatal编程技术网

C 在结构数组中输入字符的循环无法正常工作

C 在结构数组中输入字符的循环无法正常工作,c,arrays,loops,structure,C,Arrays,Loops,Structure,字典程序应该读取用户输入的单词作为单词或定义。唯一的问题是,对于循环的第一个实例,似乎没有调用readLine函数,并且只有当单词必须存储在字典[0]中时才会发生这种情况。它跳过让用户输入条目1的单词 我怎样才能解决这个问题 // Enter words with their corresponding definitions #include <stdio.h> struct entry { char word[15]; char definition[50];

字典程序应该读取用户输入的单词作为单词或定义。唯一的问题是,对于循环的第一个实例,似乎没有调用readLine函数,并且只有当单词必须存储在字典[0]中时才会发生这种情况。它跳过让用户输入条目1的单词

我怎样才能解决这个问题

// Enter words with their corresponding definitions

#include <stdio.h>

struct entry
{
    char word[15];
    char definition[50];
};



int main (void)
{
    int numberEntries;

    void inputEntry (struct entry dictionary[], int numberEntries);


    printf ("How many dictionary entries do you want to enter?.\n");
    scanf ("%i", &numberEntries);

    struct entry dictionary[numberEntries];

    inputEntry (dictionary, numberEntries);

    return 0;

}




void inputEntry (struct entry dictionary[], int numberEntries)
{
    void readLine (char buffer[]);
    int i;

    for ( i = 0; i < numberEntries; i++ ) {
        printf ("Entry #%i:\n", i + 1);
        printf ("Word: ");
        readLine (dictionary[i].word);

        printf ("Definition: ");
        readLine (dictionary[i].definition);

        printf ("\n");
    }

    for ( i = 0; i < numberEntries; i++ ) {
        printf ("\n%s", dictionary[i].word);
        printf ("\n%s", dictionary[i].definition);

    }

}

// Get a string and save it in an array

void readLine (char buffer[])
{
    char character;
    int i = 0;

    do
    {
        character = getchar ();
        buffer[i] = character;
        i++;
    }
    while ( character != '\n' );

    buffer[i - 1] = '\0';
}
您正在混合使用scanf和getchar,这会使事情变得混乱。scanf将只读取键入的整数,然后下一个getchar将读取Enter keypress作为\n

在您的情况下,最简单的解决方案是使用readLine而不是scanf


您也可以考虑使用标准函数FGET,而不是编写自己的读行。fgets更好,因为您的函数不对buffer参数进行边界检查,如果在一行中键入太多字符,则会导致缓冲区溢出。

使用scanf后从输入缓冲区中删除换行符的另一种方法是使用getchar。建议您在需要第二次读取标准DIN时使用:

char c;
...
scanf ("%i", &numberEntries);
do {
    c = getchar();
} while ( c != '\n');
然后,您将能够毫无问题地输入第一个单词:

./bin/dict
How many dictionary entries do you want to enter?.
3
Entry #1:
Word: dog
Definition: wags tail

Entry #2:
Word: cat
Definition: meows constantly

Entry #3:
Word: mouse
Definition: does little


dog
wags tail
cat
meows constantly
mouse
does little

你能运行程序吗?不,我现在不能运行你的代码。但是,这是一个常见的问题,问题的原因很清楚。虽然程序可以改进,但我认为主要问题与数组结构中的保存有关是的,我的建议将解决您描述的问题。你试过我的建议了吗?