What I'm trying to accomplish is to take no more than "x" characters (spaces included) as input. I only know how to do both of them separately with scanf
,
like the following:
scanf("%20s",str)
This takes no more than 20 characters.
scanf("%[^\n]s",str)
takes spaces as well, but it has no limit.
I tried getline
but it takes the \n
as a value in the string as well and I don't want that. I hope I was clear enough about what I'm asking.
From what @chqrlie has told me I wrote this fuction:
void getstring(char *str, int len)
{
do
{
if (fgets(str, len, stdin))
{
fflush(stdin);
// if is not the first character to be the new line then change it to '\0' which is the end of the string.
if (str[0] != '\n')
str[strcspn(str, "\n")] = '\0';
}
}while (str[0] == '\n'); // Check if the user has inserted a new line as first character
}