Created
June 10, 2025 20:52
-
-
Save BolvarsDad/0ba2658d102d05ce815ce2e64d94a471 to your computer and use it in GitHub Desktop.
Single-line input in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
size_t | |
get_line(char *buffer, size_t bufsz) | |
{ | |
static char ch; | |
size_t nread; | |
size_t buflen = 0; | |
while (buflen < bufsz) { | |
if ((nread = fread(&ch, sizeof ch, 1, stdin)) == 0 || ch == '\n') | |
break; | |
buffer[buflen++] = ch; | |
} | |
return buflen; | |
} | |
int | |
main(int argc, char **argv) | |
{ | |
char buf[10]; | |
size_t nread; | |
nread = get_line(buf, 10); | |
printf("Result: {'%.*s', %lu}\n", (int)nread, buf, nread); | |
printf("Expected: {'Hello Worl', 10}\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment