为什么以下代码不允许我使用fgets获得用户输入,但不能使用scanf? [英] Why is the following code not allowing me to get user input with fgets yet works with scanf?

查看:45
本文介绍了为什么以下代码不允许我使用fgets获得用户输入,但不能使用scanf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个较大程序的简短摘录,但是该程序的其余部分无关紧要,因为我认为我能够隔离该问题.我怀疑这与我使用fgets的方式有关.我已经读过,最好使用fgets而不是scanf,但是我似乎无法使其在这里正常工作.当我使用以下代码时,该程序没有给我输入数字的机会(而只是跳到了while循环,该循环检查输入的数字是否在正确的范围内):

This is a short excerpt from a bigger program, but the rest of the program is irrelevant since I think I was able to isolate the issue. I suspect that it has something to do with the way I'm using fgets. I've read that it's preferable to use fgets over scanf, but I can't seem to get it to work properly here. When I use the following code, the program doesn't give me a chance to enter the number (but simply skips to the while loop which checks if the number entered is in the correct range):

#include <stdio.h>
#include <stdlib.h>

#define SIZE 10

int main(void)
{
    // ask user for how many items to store
    printf("how many words would you like to enter? (1-%i): ", SIZE);

    // save number of words user would like to store
    char *input = malloc(sizeof(char));
    fgets(input, 1, stdin);
    // scanf("%c", input);

    int words = atoi(input);

    printf("the number of words is: %i\n", words);
    while (words < 1 || words > SIZE)
    {
        printf("please enter a number between 1 and %i: ", SIZE);
        scanf("%i", &words);
    }
}

这是我得到的输出:

~/workspace/extra_stuff/hash_tables/ $ ./test2
how many words would you like to enter? (1-10): the number of words is: 0
please enter a number between 1 and 10: 

如您所见,它从不让我输入数字,而只是假设我没有输入任何内容,便继续进行下一步.

As you can see, it never let me enter the number, but simply moved on to the next step seemingly assuming I didn't enter anything.

如果我按以下方式更改代码,则一切按计划进行:

If I change the code as follows, everything works as planned:

#include <stdlib.h>

#define SIZE 10

int main(void)
{
    // ask user for how many items to store
    printf("how many words would you like to enter? (1-%i): ", SIZE);

    // save number of words user would like to store
    char *input = malloc(sizeof(char));
    // fgets(input, 1, stdin);
    scanf("%c", input);

    int words = atoi(input);

    printf("the number of words is: %i\n", words);
    while (words < 1 || words > SIZE)
    {
        printf("please enter a number between 1 and %i: ", SIZE);
        scanf("%i", &words);
    }
}

P.S .:我确实意识到,如果使用scanf,我可以立即使用atoi将输入存储到一个不带int变量的int变量中,以将char转换为int.但是,fgets似乎需要一个char *,因此这就是我选择此路由的原因.另外,我意识到我应该稍后 free(input).

P.S.: I do realize that if using scanf, I could immediately store the input to an int variable w/o using atoi to convert char to int; however it seems that fgets requires a char *, so that's why I chose this route. Also, I realize that I'm supposed to free(input) later.

有人可以解释这种行为吗?谢谢.

Can someone explain this behavior? Thanks.

感谢迄今已回答的每个人!那里有一些有用的建议,但看起来我的程序中还有同样的问题.这是代码摘录:

Thanks to everyone who has replied so far! Some helpful suggestions there, but it looks like I'm having the same issue further in my program. Here's the code excerpt:

// ask for strings
    for (int j = 0; j < words; j++)
    {
        char buffer[4096];
        // fgets(buffer, 40, stdin);

        // name=calloc(NAME_SIZE, sizeof(char));
        // fgets(name, NAME_SIZE, stdin);

        // printf("size of (array[j]->next)->text is: %lu\n", sizeof((array[j]->next)->text));

        printf("please enter string #%i: ", j);

        fgets(buffer, 4096, stdin);

        printf("you've entered: %s", buffer);

        int length = strlen(buffer);
        printf("word length: %i\n", length); 
}

当我运行程序时,它本来不会给我输入以下内容的机会:

When I run the program, it once again doesn't give me a chance to enter my input when it's supposed to:

please enter string #0: you've entered: 
word length: 1


编辑#2:

研究了David的答案并引用了其他人的评论和其他SO线程之后,我提出了以下版本的代码,该版本首先要求用户输入想要输入的单词数(并进行验证输入),然后要求用户输入这些单词(再次验证输入内容).它似乎正在编译时没有错误和警告并且可以正常运行,尽管我不是100%肯定我已经测试了用户输入可能出错的所有可能情况,并且我仍然不了解其中的一些代码尚不完全了解(我将在下面列出)-如果有人有时间/意愿/耐心进行检查,并告诉我是否仍然可以改善某些方面,请告诉我.我的目标是在另一个程序中使用此代码,该程序将要求用户输入并将条目存储在哈希表中.

After working through David's answer and referencing other people's comments and other SO threads, I've come up with the following version of the code, which first asks the user for the number of words they'd like to enter (and validates the input) and then asks the user to enter those words (again, validating the input). It seems to be compiling w/o errors and warnings and functioning properly, though I am not 100% sure I've tested all the possible things that could go wrong with the user input, and there are some bits of the code I still don't completely understand (I'll list them below) -- if anyone has time/desire/patience to look through it and tell me if I can still improve something, please let me know. My goal is to use this code in another program that will ask for user input and store the entries in a hash table.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUF_SIZE_WORDS 4096
#define BUF_SIZE_NUMBERS 256
#define MAX_WORDS 10

int word_input(int num_words);

void empty_stdin();

int main(void)
{
    int num_words = 0,       /* number of words to enter */
        word_count_check = 0;          /* word count */

    char buffer[BUF_SIZE_NUMBERS] = "";    /* buffer of sufficient size for input */

    for (;;) /* loop continually until valid input of NUMBER OF WORDS USER WANTS TO ENTER or user cancels */
    {
        printf ("how many words would you like to enter? [1-%d]: ", MAX_WORDS);
        // check for cancellation of input
        if (!fgets (buffer, BUF_SIZE_NUMBERS, stdin))
        {
            fputs ("user canceled input\n", stderr);
            return 1;
        }

        // check if user simply hit enter w/o typing anything
        if(buffer[0] == '\n')
        {
            printf("please enter a value\n");
            continue;
        }


        size_t inlength = strlen(buffer);

        // validate length < BUF_SIZE_NUMBERS - 1
        if (inlength >= BUF_SIZE_NUMBERS - 1)
        {
            fputs ("input exceeds allocated buffer size\n", stderr);
            return 2;
        }

        if (inlength && buffer[inlength - 1] == '\n')
        {
            // printf("hurray!\n");
            buffer[--inlength] = 0;
        }
        else if (inlength == BUF_SIZE_NUMBERS - 1) /* the line was too long */
        {
            printf("you've entered too many characters... please stick to a maximum of %i\n", BUF_SIZE_NUMBERS);
            empty_stdin();
            continue;
        }

        // make sure user actually entered a proper int
        if (sscanf (buffer, "%d", &num_words) != 1) /* sscanf is used for conversion */
        {
            fputs ("invalid conversion to int; please provide valid input\n", stderr);
            continue;
        }

        // check if the number entered is out of range
        if (num_words < 1 || num_words > MAX_WORDS)
            fprintf (stderr, "%2d out of valid range.\n", num_words);
        else
            break; /*if the input has been validated, we can now break out of the for loop */
    }

    // call the word_input function and store its return value in word_count_check
    word_count_check = word_input(num_words);

    // check if the number of words processed equals to the number requested by the user
    if(word_count_check == num_words)
    {
        printf("success!\n");
    }
    else
    {
        printf("something went wrong, since word_count_check != num_words...\n");
    }

}

int word_input(int num_words)
{
    int word_count = 0;

    for(;;) /* loop until word_count == num_words is achieved */
    {
        // declare an array for storing input string
        char buffer[BUF_SIZE_WORDS];
        char valid_input[BUF_SIZE_WORDS];

        // prompt user for input
        printf("please enter a string: ");

        // get input and check for CTRL+D
        if (!fgets(buffer, BUF_SIZE_WORDS, stdin))
        {
            fputs ("user canceled input\n", stderr);
            exit(1);
        }

         // check if user simply hit enter w/o typing anything
        if(buffer[0] == '\n')
        {
            printf("please enter a word that's more than 0 characters\n");
            // empty_stdin();
            continue;
        }

        size_t inlength = strlen(buffer);

        // check if user input exceed buffer size
        if (inlength >= BUF_SIZE_WORDS - 1)
        {
            empty_stdin();
            fputs ("input exceeds allocated buffer size, please try again\n", stderr);
            continue;
        }

        // check if the user entered too many characters
        if (inlength == BUF_SIZE_WORDS - 1) /* the line was too long */
        {
            printf("you've entered too many characters... please stick to a maximum of %i\n", BUF_SIZE_WORDS);
            empty_stdin();
            continue;
        }

        if (inlength && buffer[inlength - 1] == '\n')
        {
            buffer[--inlength] = 0;

            // get rid of trailing spaces using sscanf
            sscanf(buffer, "%s", valid_input);

            // figure out the length of the word the user entered
            int word_length = ((int) strlen(valid_input));
            printf("string length: %i\n", word_length);

            // print out the word entered by the user one character at a time
            printf("you've entered: ");
            for (int i = 0; i < word_length; i++)
            {
                printf("%c", valid_input[i]);
            }
            printf("\n");

            // increment word count
            word_count++;
            printf("word_count = %i\n", word_count);

            if (word_count == num_words)
            {
                return word_count;
            }
        }
    }
}

/* helper function to remove any chars left in input buffer */
void empty_stdin()
{
    int c = getchar();
    while (c != '\n' && c != EOF)
        c = getchar();
}

我尚不完全了解的事情:

things I don't completely understand yet:

1)

if (!fgets (buf, MAXC, stdin)) { /* validate ALL user input */ 
    fputs ("(user canceled input)\n", stderr); 
    return 1; 
}

---这是否只是检查用户是否手动输入了EOF(使用ctrl + d),还是也检查了其他内容?

--- does this simply check if the user manually entered EOF (with ctrl+d), or does it check for something else too?

2)调用下面的empty_stdin()函数似乎导致某种奇怪的挂起,看起来程序正在期待我的进一步输入,而不是继续进行下一步,尤其是当我经常使用它(我想出了为什么每次用户键入奇怪的内容时都不清除输入流?)和/或当我将缓冲区减小到很小的地方然后有目的地输入了太多字符时.

2) calling the empty_stdin() function below seemed to be causing some kind of a weird hang-up where it looked like the program was expecting further input from me as opposed to just going on to the next step, especially when I used it frequently (I figured why not clear the input stream every time the user types in something weird?) and/or when I decreased the buffer to something very small and then purposefully entered too many characters..

void empty_stdin()
{
    int c = getchar();
    while (c != '\n' && c != EOF)
        c = getchar();
}

3)最终,我想使用其中的一些代码从文本文件(而不是用户输入)中加载字典,并将其存储在哈希表中,并在另一个版本中存储在trie中.除了使用isalpha()来确保我们只存储其中包含字母的单词之外,在处理输入时,除了上述内容之外,还需要进行其他检查/验证吗?是否应跳过以上任何一项检查?

3) eventually I want to use some of this code to load a dictionary from a text file (instead of user input) and store it in a hash table, and, in another version, in a trie. Besides using isalpha() to make sure we're only storing words that have letters in them, are there any other checks/validations that need to happen when processing the input, beside the ones above? Should any of the above checks be skipped?

推荐答案

在C语言中处理字符串没有任何魔力-但是您确实需要戴上帽子...为什么?在处理输入时,不仅要考虑放入缓冲区(或存储输入的任何位置)中的字符数,而且还必须考虑输入流中剩余的字符!

There is no magic involved in dealing with strings in C -- but you do need to put your accounting hat on... Why? When dealing with input, you have to not only account for the number of characters that you place into your buffer (or wherever you are storing your input), but you also must account for the characters that remain in your input stream!

当使用任何 scanf 系列功能进行输入时,尤其如此.为什么?由于发生 matching input 失败时,处理(读取和删除)输入缓冲区中的字符(此处为 stdin )停止,不会再读取任何字符,并且导致 matching 失败的任何字符在输入流中仍然未读,只是在下次尝试读取时再次咬你.

This is particularly true when using any of the scanf family of function for input. Why? Because on a matching or input failure, processing (reading and removing) characters from your input buffer (stdin here) stops, no further characters are read, and any character causing the matching failure remains unread in your input stream, just waiting to bite you again on your next attempted read.

一些新的转换说明符消耗了领先的空白(例如,空格,制表符,换行符,... ),其他则没有.您的数字转换说明符(以及%s" )占用前导空格,而%c" %[...]"不.

Compounding this bewilderment for new C programmers is the fact that some conversion specifiers consume leading whitespace (e.g. space, tab, newline,...) and others do not. Your numeric conversion specifiers (along with "%s") consume leading whitespace while "%c" and "%[...]" do not.

所有这些都是鼓励新的C程序员使用诸如 fgets 或POSIX getline 之类的 line-aligned 输入函数的主要原因.用户输入(因为他们一次读取整行-包括试用版的'\ n')使新程序员不必考虑结束空格或冒犯了在转换时无法转换的字符,从而解放了他们匹配失败...

All of which are the primary reasons new C programmers are encouraged to use line-oriented input functions like fgets or POSIX getline to handle user input (because they read the entire line at a time -- including the trialing '\n') freeing the new programmer for having to account for ending whitespace or offending characters not converted in the event of a matching failure...

使用 fgets 后跟 sscanf 提供了额外的好处,即允许对(1)的输入进行单独的 validation 验证;(2)将输入解析并转换为所需的值.

Using fgets followed by a sscanf provides the additional benefit of allowing separate validation of (1) the read of input; and (2) the parse and conversion of input into the needed values.

(注意:具有面向行的输入功能的唯一警告是,它们读取并包含尾随的'\ n'填充到缓冲区中-因此您需要根据需要修剪"尾随空白.您不希望流浪'\ n'字符悬空在行尾您存储的字符串.)

(note: the only caveat with line-oriented input functions is that they read and include the trailing '\n' in the buffer they fill -- so you will need to "trim" the trailing whitespace as required. You don't want stray '\n' characters dangling off the end of the strings you are storing.)

也就是说,有时候使用 scanf 函数系列读取输入是有意义的.只要您每次 验证 退货并处理所有三种可能的条件

That said, there will be times when reading input with the scanf family of functions makes sense. There is nothing wrong with doing so, so long as you validate the return every time and handle all three possible conditions:

  1. 用户在Linux上按 ctrl + d 可以生成手动 EOF (在windoze上为 ctrl + z );
  2. 您可以处理匹配输入失败的情况,包括在下一次尝试读取之前从输入缓冲区中删除所有有害字符;最后
  3. 您输入的信息很好(返回值表示所有预期的转换已发生).
  1. the user presses ctrl+d on Linux to generate a manual EOF (ctrl+z on windoze);
  2. you handle the matching or input failure cases, including removing any offending characters from your input buffer before your next attempted read; and finally
  3. you have good input (the return indicates all the conversions anticipated, took place).

这没有什么魔术,但是它确实需要了解可能的错误情况并在每次输入时处理每个错误情况.

There is no magic to any of it, but it does take understanding the possible error conditions and handling each of them on every input.

在您的情况下,让我们看一下获取用户输入的单词数的任务.在这里,您尝试使用 fgets 进行读取(很好!),但是您没有提供足够的存储空间来保存输入.当从用户那里读取少量文本时,您只需要一个具有自动存储类型的简单数组即可.但是,您需要相应地调整缓冲区的大小(并且不要跳过缓冲区的大小).

In your case, let's look at your task of getting the number of words to enter from the user. Here you were attempting to read with fgets (that's good!), but you failed to provide sufficient storage to hold the input. When reading small amount of text from the user, a simple array with automatic storage type is all you need. However, you need to size the buffer accordingly (and do NOT skimp on buffer size).

没有黄金法则,但是如果我让用户输入文本以将其转换为单个数字,那么使用 256 字符缓冲区(可以提供足以容纳输入的字符缓冲区),我会感到很好有效数字,再加上230个奇数字符来处理猫踩键盘的时间,等等.

There is no golden rule, but if I had users entering text to convert to a single number, then I would feel good with a 256 character buffer (which provides more than enough to hold the input of any valid number, plus another 230 some-odd characters to handle the time the cat steps on the keyboard, etc..)

例如,可以通过类似于以下内容的方式来获取用户的输入并获取要输入的单词数:

For example, taking input from the user and getting the number of words to enter could be done in a manner similar to the following:

#include <stdio.h>

#define SIZE  10    /* good form defining a constant! */
#define MAXC 256    /* max characters for buffer */

int main (void) {

    int nwords = 0,         /* number of words to enter */
        words = 0,          /* each word */
        wc = 0;             /* word count */
    char buf[MAXC] = "";    /* buffer of sufficient size for input */

    for (;;) {  /* loop continually until valid input or user cancels */
        printf ("number of words to enter? [1-%d]: ", SIZE);
        if (!fgets (buf, MAXC, stdin)) {    /* validate ALL user input */
            fputs ("(user canceled input)\n", stderr);
            return 1;
        }
        /* validate length < MAXC - 1 and buf[length-1] == '\n' here */

        if (sscanf (buf, "%d", &nwords) != 1) { /* sscanf for conversion */
            fputs ("  error: invalid conversion to int.\n", stderr);
            continue;
        }
        if (nwords < 1 || SIZE < nwords)  /* validate nwords in range */
            fprintf (stderr, " %2d out of valid range.\n", nwords);
        else  /* good input received, break loop */
            break;
    }

(注意:您的 while 循环已转换为一个循环,该循环将连续循环,直到 1< value< SIZE 之间的有效输入为止.>输入.这种情况只是导致控制 break; 在收到良好输入时的循环)

(note: your while loop has been converted to a loop that will loop continually until valid input between 1 < value < SIZE is entered. The condition simply causes control to break; the loop at the point good input is received)

此循环展示了经典的 fgets/sscanf 从用户输入的输入行读取和解析信息.您可以按自己喜欢的任何方式从行中解析数字(但不要使用 atoi() -它提供了转换的绝对错误检查).您可以使用 strtol (经过适当的验证),并且只需使用指针即可向下移动缓冲区,挑选出数字,将其从ASCII转换为数字值,然后乘以10并随手添加.只要您验证,验证,验证操作的每个部分,就可以.

This loop presents a classic fgets/sscanf read and parse of information from the line of input entered by the user. You can parse the number from the line any way you like (but don't use atoi() -- it provides absolutely zero error checking of the conversion). You can use strtol (with proper validation) and you can simply use a pointer to walk-down-the-buffer, picking out digits, converting them from their ASCII to numeric value and then multiplying by 10 and adding as your go. Any way is fine so long as you validate, validate, validate each part of the operation.

现在转向阅读用户应该输入的每个单词,我们将忽略常规知识,并使用 scanf 来完成任务,但是我们将处理三种可能的情况每次都返回.我们还将添加一个计数器,以跟踪用户提供的有效输入,并且仅当我们提供了一定数量的有效整数(或用户通过生成手动 EOF 取消)时,才退出循环.

Now turning to reading each of the words the user is supposed to enter, we will ignore conventional wisdom and use scanf for the task, but we will handle all three possible cases of the return every time. We will also add a counter to keep track of the valid inputs provided by the user and only exit the loop when we have that number of valid integers provided (or the user cancels by generating a manual EOF).

    printf ("\nnumber of words entered: %d\n", nwords);
    for (; wc < nwords;) {  /* loop continually  */
        int rtn = 0;    /* scanf return */
        printf ("please enter a number between 1 and %d: ", SIZE);
        rtn = scanf ("%d", &words);     /* valdate ALL user input */
        if (rtn == EOF) {           /* handle EOF (manual) */
            fputs ("(user canceled input)\n", stderr);
            break;
        }
        else if (rtn == 0) {    /* handle "matching failure" */
            int c = getchar();  /* remove offending chars from stdin */
            while (c != '\n' && c != EOF)
                c = getchar();
            fputs ("  error: invalid integer input\n", stderr);
            continue;
        }
        else {  /* valid integer received */
            int c = getchar();      /* remove any extra chars from stdin */
            while (c != '\n' && c != EOF)
                c = getchar();
            if (words < 1 || SIZE < words)  /* validate in-range */
                fprintf (stderr, " %2d - invalid! (1 < valid < %d)\n", 
                        words, SIZE);
            else    /* good input, increment word count */
                printf (" word[%2d]: %3d\n", ++wc, words);
        }
    }

注意:可以清空 stdin 中任何令人反感的字符,这是一种便捷的功能,因此您不必在每次需要清除循环时重复循环在输入例程中输入 stdin .您可以将其替换为简单的功能,例如

Note: the emptying of any offending characters from stdin can be turned into a convenient function so that you do not have to duplicate the loops each time you need to clear stdin during your input routine. You can replace it with a simple function, e.g.

/* helper function to remove any chars left in input buffer */
void empty_stdin()
{
    int c = getchar();
    while (c != '\n' && c != EOF)
        c = getchar();
}

这将有助于保持代码整洁.我让您将其合并到上面.

That will help keep your code tidy. I'll let you incorporate that above.

将其完全放在一起,您可以执行以下操作:

Putting it altogether, you could do something like the following:

#include <stdio.h>

#define SIZE  10    /* good form defining a constant! */
#define MAXC 256    /* max characters for buffer */

int main (void) {

    int nwords = 0,         /* number of words to enter */
        words = 0,          /* each word */
        wc = 0;             /* word count */
    char buf[MAXC] = "";    /* buffer of sufficient size for input */

    for (;;) {  /* loop continually until valid input or user cancels */
        printf ("number of words to enter? [1-%d]: ", SIZE);
        if (!fgets (buf, MAXC, stdin)) {    /* validate ALL user input */
            fputs ("(user canceled input)\n", stderr);
            return 1;
        }
        /* validate length < MAXC - 1 and buf[length-1] == '\n' here */

        if (sscanf (buf, "%d", &nwords) != 1) { /* sscanf for conversion */
            fputs ("  error: invalid conversion to int.\n", stderr);
            continue;
        }
        if (nwords < 1 || SIZE < nwords)
            fprintf (stderr, " %2d out of valid range.\n", nwords);
        else 
            break;
    }

    printf ("\nnumber of words entered: %d\n", nwords);
    for (; wc < nwords;) {  /* loop continually  */
        int rtn = 0;    /* scanf return */
        printf ("please enter a number between 1 and %d: ", SIZE);
        rtn = scanf ("%d", &words);     /* valdate ALL user input */
        if (rtn == EOF) {           /* handle EOF (manual) */
            fputs ("(user canceled input)\n", stderr);
            break;
        }
        else if (rtn == 0) {    /* handle "matching failure" */
            int c = getchar();  /* remove offending chars from stdin */
            while (c != '\n' && c != EOF)
                c = getchar();
            fputs ("  error: invalid integer input\n", stderr);
            continue;
        }
        else {  /* valid integer received */
            int c = getchar();      /* remove any extra chars from stdin */
            while (c != '\n' && c != EOF)
                c = getchar();
            if (words < 1 || SIZE < words)  /* validate in-range */
                fprintf (stderr, " %2d - invalid! (1 < valid < %d)\n", 
                        words, SIZE);
            else    /* good input, increment word count */
                printf (" word[%2d]: %3d\n", ++wc, words);
        }
    }
}

使用/输出示例

$ ./bin/getintstdin
number of words to enter? [1-10]: five, maybe six?
  error: invalid conversion to int.
number of words to enter? [1-10]: -2
 -2 out of valid range.
number of words to enter? [1-10]: 3

number of words entered: 3
please enter a number between 1 and 10: two? three?
  error: invalid integer input
please enter a number between 1 and 10: 2
 word[ 1]:   2
please enter a number between 1 and 10: -2
 -2 - invalid! (1 < valid < 10)
please enter a number between 1 and 10: 11
 11 - invalid! (1 < valid < 10)
please enter a number between 1 and 10: 3
 word[ 2]:   3
please enter a number between 1 and 10: 4
 word[ 3]:   4

请注意上面所有无效的输入以及代码如何处理每个无效输入.只要使用 fgets 输入的字符数不超过255个字符,代码就会正常响应无效的整数输入(无论给出多少个),并且将响应超出整数的输入-范围.

Note all the invalid inputs above and how the code handles each. So long as the input does not exceed 255-characters with fgets, the code will gracefully respond to inputs that are not valid integers (regardless how many are given) and it will respond to integer inputs that are out-of-range.

该代码的长度不超过您发布的代码,但是它解决了可能出现的错误情况,然后处理了这些错误.当您将其全部煮沸时,这就是编码的全部意义所在.仔细研究一下,如果您还有其他问题,请告诉我.

The code isn't much longer than the code you posted, but it addresses the possible error conditions that could arise and then handles the errors. When you boil it all down, that is what coding is all about. Look things over and let me know if you have further questions.

这篇关于为什么以下代码不允许我使用fgets获得用户输入,但不能使用scanf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆