The following is my attempt at writing a getline()
function that makes it a bit easier to work with. I suppose an easier way would be to use fgets
, but hopefully the following is good enough for some feedback:
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#define TITLE_MAX 50
void mygets(char buffer[], size_t limit)
{
// first non-space char until newline or EOF,
// eating any extra chars in buffer
// will add \0 at the end, so will get up to N-1 chars
int c, idx=0;
bool started=false;
while ((c=getchar()) != EOF && c != '\n')
{
if (!started && isspace(c));
if (idx < limit-1) {
started = true;
buffer[idx++] = c;
}
}
buffer[idx] = '\0';
}
int main(void)
{
char tbuffer[TITLE_MAX];
while (true)
{
printf("Enter the name of the film (empty line to stop)\n");
mygets(tbuffer, TITLE_MAX);
if (*tbuffer=='\0') break;
printf("The title is: %s\n", tbuffer);
}
}
Working example on onlinegdb
How does it look? How could it be improved? Additionally, how are comments usually done in C code? It is usually within the function braces? Before the function? etc.
"\n"
? \$\endgroup\$if (!started && isspace(c));
? \$\endgroup\$\s
being used to mean space):\s\s\s Hello, chux
-->Hello, chux
. But it looks like that's bad code and there's an error within it. \$\endgroup\$'\n'
) as with" ABC \n"
? \$\endgroup\$