读取多行直到EOF

问题描述 投票:1回答:1
#include <stdio.h>
#include <stdlib.h>
#include <string.h> 

//the function
char* scan(char *string)
{
  int c; //as getchar() returns `int`
  string = malloc(sizeof(char)); //allocating memory

  string[0]='\0';

  for(int i=0; i<100 && (c=getchar())!='\n' && c != EOF ; i++)
  {
    string = realloc(string, (i+2)*sizeof(char)); //reallocating memory
    string[i] = (char) c; //type casting `int` to `char`
    string[i+1] = '\0'; //inserting null character at the end
  }

  return string;
}
char** bigScan(char **string)
{

  int c;
  string=malloc(sizeof(char *));
  string[0]='\0';
  for(int i=0;(c=getchar()!=EOF);i++)
  {
    *string = realloc(string, (i+2)*sizeof(char *)); //reallocating memory
    string[i] = scan(string[i]); //type casting `int` to `char`
    string[i+1] = '\0'; //inserting null character at the end

  }
  return string;

}
int main(void)
{
  char **buf; //pointer to hold base address of string
  buf=bigScan(buf);
  printf("%s\n",buf[0] );


}

所以基本上扫描函数读取每一行直到EOF或新行.bigScan的工作是通过调用扫描函数读取多行(指向字符串的指针),直到我们点击EOF。所以基本上大扫描会返回指向指针的指针,我们可以使用它来读取整个文本。在我的方法中我做错了什么?基本上在我的bigScan中调用扫描功能,直到我点击EOF。

  Ideal Input:
  "Hi guys and girls
  This is a message in multiple lines."
  Ideal Output:
  "Hi guys and girls
  This is a message in multiple lines."
c malloc stdout stdin
1个回答
2
投票
  1. (c=getchar()!=EOF)内的bigScan无效。它将10的值赋给c,因为bool值是!=比较的结果。
  2. qazxsw poi中的qazxsw poi会让你每行丢失一个角色,因为那个角色无处可挽救。
  3. getchar()的分配无效。你不应该为字符串bigScan分配内存,但你应该为指针本身分配内存,即。 bigScan
  4. *string = realloc(string是用于指针的终止值。不要使用string = realloc(string, ... sizeof(char*))作为指针。
  5. 使用NULL存储大小。
  6. 如果要覆盖它们,传递参数值几乎没有意义。在此函数中,变量'\0'未使用size_t,因为两个函数中的变量a在进入函数后立即分配。
  7. 函数void f(int a) { a = 1; }具有string字符的硬限制。

以下是您的功能的某种固定版本。同时也重命名了变量。并删除参数。和不同的缩进。并使用标准scan中的i<100ions作为原始错误检查。而使用assert所以在#include <assert.h>中读取的字符不会消失。我没有运行此代码,因此它有很多错误。

ungetc
© www.soinside.com 2019 - 2024. All rights reserved.