如何通过终端将段落作为 C 中的单个字符串读取? [英] How can I read a paragraph in via the terminal as a single string in C?

查看:39
本文介绍了如何通过终端将段落作为 C 中的单个字符串读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 C 程序,该程序应该阅读用户的一篇文章.文章分为多个段落.我不知道这篇文章有多少行或多少个字符,但我知道它以哈希符号 (#) 结尾.我只想使用保存文章所需的内存.

I'm writing a C program that should read in an essay from a user. The essay is divided into multiple paragraphs. I don't know how many lines or characters the essay will be, but I do know that it ends with a hash symbol (#). I want to use only as much memory as is necessary to hold the essay.

这是我迄今为止尝试过的:

Here is what I have tried so far:

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


main(){

    int size;
    char *essay;

    printf("\n how many characters?\n");
    scanf("%d", &size);
    essay =(char *) malloc(size+1);
    printf("Type the string\n");
    scanf("%s",essay);

    printf("%s",essay );

}

我之前说过,我不知道(也不想问)关于字符数的问题.如何动态分配内存以节省空间?(什么是动态内存分配?)有没有其他不依赖动态分配的内存节省方式?

As I said before, I don't know (and don't want to ask) about the number of characters beforehand. How do I dynamically allocate memory to save space? (What is dynamic memory allocation?) Is there another way to save memory that doesn't rely on dynamic allocation?

此外,我的代码现在一次只能读取一行.如何读取多行并将它们存储为单个字符串?

Additionally, my code only reads one line at a time right now. How can I read multiple lines and store them as a single string?

这是另一个代码

#include <stdio.h>    
#include <stdlib.h>    
int main ()
{
  char input;
  int count = 0;
int n;
  char* characters= NULL;
  char* more_characters = NULL;
  do {
     printf ("type the essay:\n");
     scanf ("%d", &input);
     count++;

       more_characters = (char*) realloc (characters, count * sizeof(char));
      if (more_characters!=NULL) {
       characters=more_characters;
       characters[count-1]=input;  }
     else {
       free (characters);
       printf ("Error (re)allocating memory");
       exit (1);
     }
  } while (input!='#');

printf ("the essay: ");
    for (n=0;n<count;n++) printf ("%c",characters[n]);
    free (characters);
   }

它不起作用

推荐答案

嗯,不要浪费内存空间",

Hmmm to "not waste space in memory",

那么过度调用realloc()怎么办?

char *Read_Paragraph_i(void) {
  size_t size = 0;
  size_t i = 0;
  char *dest = NULL; 
  int ch;
  while ((ch = fgetc(stdin)) != EOF) {
    if (ch == '#') break;
    size++;
    char *new_ptr = realloc(dest, size);
    assert(new_ptr);
    dest = new_ptr;
    dest[i++] = ch;
  }
  size++;
  char *new_ptr = realloc(dest, size+);
  assert(new_ptr);
  dest = new_ptr;
  dest[i++] = '\0';
  return dest;
}

更明智的方法是每次需要更多内存时将分配大小加倍,暂时浪费内存,然后是最终正确大小"的分配.

A more sane approach would double the allocation size every time more memory is need, temporally wasting memory and then a final "right-size" allocation.

这篇关于如何通过终端将段落作为 C 中的单个字符串读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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