use getchar
, malloc
and realloc
for reading the unlimited input string
Declare String type, you can also use char *
// String type
typedef char *String;
I write this function for joining the char in the end of string
/**
* Join the Char into end of String
*
* @param string - String
* @param c - joined char
*/
void String_joinChar(String *string, const char c)
{
const size_t length = strlen(*string);
(*string) = (String)realloc((*string), sizeof(char) * (length + 2));
(*string)[length] = c;
(*string)[length + 1] = '\0';
}
This function for inputting string, which read the char from keyboard by using getchar
and join it in the end of current string.
/**
* Input String
*
* @return Inputed String
*/
String String_input()
{
String string = (String)malloc(sizeof(char));
strcpy(string, "");
char cursor;
fflush(stdin);
while ((cursor = getchar()) != '\n' && cursor != EOF)
{
String_joinChar(&string, cursor);
}
return string;
}
Cause of using char *
, malloc
and realloc
, we must free it
/**
* Destroy String
*
* @param string - Destroyed String
*/
void String_destroy(String string)
{
free(string);
}
And now we just use it !!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
String string = String_input();
printf("\n%s\n", string);
String_destroy(string);
return 0;
}
Hope useful to you!
char
long and phone numbers with dozens of digits. But allowing unlimited input invites hackers to overwhelm systems with billion long names/titles etc. Far better to allow for exceptional, even pathological long input, but not unlimited.fgets(user_name, 1000, stdin)
is sufficient. – Agnosticgets
does not let you specify the size of the target array. That's what makes it inherently unsafe, which is why it's been removed from the language as of the 2011 ISO C standard. Were you thinking offgets
? – Propylene