我正在编写一个 C 程序,该程序应该读取用户的文章。这篇文章分为多个段落。
我不知道这篇文章有多少行或字符,但我知道它以井号(#
)结尾。我只想使用容纳论文所需的内存。
这是我迄今为止尝试过的:
#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 );
}
正如我之前所说,我事先不知道(也不想问)字符数。如何动态分配内存以节省空间? (什么是动态内存分配?)是否有另一种不依赖动态分配的方式来节省内存?
此外,我的代码现在一次只能读取一行。如何读取多行并将它们存储为单个字符串?
这是另一个代码
#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);
}
它不工作
最佳答案
您可以一次读取一个字符并将其复制到您的论文缓冲区中。当你的论文缓冲区空间不足时,你可以重新分配以获得另一 block 内存。当您读取的字符是“#”时,您就完成了。
关于c - 如何通过终端将段落读取为 C 中的单个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33645322/