I can't think, how I should go for. I need to input a long char string, I shouldn't care about the size of a string, and the end of a string is only pressing enter.
My thougths are that I should realloc() my buffer by a value, which return a getline() function. But how should I do that, if buffer waits some memory allocation before filling it?
- Allocate some memory for a
buffer - Use a
getlinefunction for getting symbols and return a value of a inputting char string If I try to realloc some memory one more time ,I think, it is not necessary because I've already typed my string.
In conclusion, I need to
type a string, then recorda string in a bufferby size whichreturn a getline()function.
Can you give a hint, how I need to go for this task, if I'm correct in my thoughts?
Code is below:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int getline(char* s, int lim);
int main()
{
char* buffer;
size_t bufSize=100;
int c;
printf("\t\t\tLong Long string!\n");
buffer=(char*)malloc(bufSize*sizeof(char));
if (buffer==NULL)
{
perror("Unable to allocate buffer\n");
exit(1);
}
printf("input smth:\n");
c=getline(buffer,bufSize);
printf("You typed: %s \n",buffer);
free(buffer);
return 0;
}
int getline(char s[], int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
{
s[i] = c;
}
if (c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
Here I just allocate buffer of char with 100*sizeof(char) and give a function getline() bufSize=100. And I can see printf("You typed: %s \n",buffer); only only a string of 100 symbols.