【问题标题】:How this example works? (Book's example of gets function)这个例子是如何工作的? (书中获取函数的示例)
【发布时间】:2018-05-24 22:23:49
【问题描述】:

特别是在while循环中

  1. getchar() 函数的输入是什么变量?如果是 's' 在哪里表达?

  2. 这个功能好用吗?我发现各种“读取”函数(如gets()、fgets() 或scanf())存在问题。这个会不会像其他人一样出现问题?

    char * mygets(char *s) {
      int i = 0, ch;
      while ((ch = getchar()) != '\n')
        s[i++] = ch;
      s[i] = '\0';
      return s;
    }
    
    main() {
      char input[21];
      printf("type anything:\n");
      mygets(input);
      printf("output: %s\n", input);
    }
    

【问题讨论】:

  • "这个功能好用吗?" --> 不,因为它会受到缓冲区溢出的影响。至少有5个缺点。然而,如果 OP 首先发布了答案似乎是什么,那就太好了。否则看起来像是在做 OP 的作业。
  • @chux 操作?好吧,我相信 s 正在提供 getchar() 函数,但我看不到向它声明此信息的位置。不,这不是家庭作业。

标签: c string function


【解决方案1】:

当您使用 getchar(3) 或 gets(3) 函数时,输入是从进程标准输入中读取的。

getchar() 函数等价于 getc(stdin)。

由于一次读取一个字符,您需要计算读取的字符数,并确保您不会“超出可用空间的尽头”。这意味着您需要传递 s 的“大小”。

char*
mygets(char *s) {
    //is s a valid pointer to memory?
    //how much space is available in s?
    int i = 0, ch;
    //what is the maximum value of an int?
    //what happens when i++ exceeds MAX_INT?
    //does -1 make sense?
    //getchar(3) can return EOF
    while ((ch = getchar()) != '\n')
        s[i++] = ch;
    s[i] = '\0';
    return s;
}

改用这样的方法。计算读取的字符数,检查是否没有超出传递缓冲区的末尾,然后

char*
mygets(char* s, const size_t size) {
    if( !s ) return s; //error, null pointer passed
    size_t count=0;
    char* sp = s;
    int ch;
    for( ; (count<size) && ((ch = getchar()) != EOF); ) {
        ++count; //count each character read, but not EOF
        if( (*sp++ = ch) == '\n' ) break; //store characters read, check for newline
    }
    *sp = '\0'; //null terminate s
    return s;
}

您应该只传递合理的大小值和合理的 s 值(至少大小的有效字符缓冲区)。用法示例:

char buffer[999];
mygets(buffer, 999); //or mygets(buffer, sizeof(buffer));

【讨论】:

    【解决方案2】:

    1) getchar() 在输入时获取一个字符....所以它“等待”您输入...在键盘上输入一个字符..

    2) 这是一个基本功能,还有更多优化和高级功能可以用字符来完成这些事情......但是如果你想正确编码,了解这里发生的事情非常重要..

    干杯...

    【讨论】:

    • getchar() 如何识别 s 参数应该喂它?
    猜你喜欢
    • 2020-07-17
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2017-11-26
    • 2021-10-14
    相关资源
    最近更新 更多