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?
this is another code
#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);
}
it is not working