How do you set a character limit for get string answers in C?

70 Views Asked by At

I'm a beginner to coding and recently came across a simple issue that I cannot find the solution to on stack overflow, nor google.

string m = get_string("Something: ");

I don't know much code so I resulted to google and stackoverflow which both didn't work unfortunately.

2

There are 2 best solutions below

0
Oka On BEST ANSWER

There is no way to directly limit the number of characters read by get_string.

Instead, you can use strlen to check the length of the resulting string, i.e.,

string foo = get_string("enter a string: ");
size_t length = strlen(foo);

if (length > 24)
{
    fprintf(stderr, "String is too long!\n");
    exit(1);
}
0
P4WN3R On

I think get string should be scanf function. Below is an example of a simple input operation in C with a maximum of 5 characters:

#include <stdio.h>

int main() {
    char input[6]; // +1 for null char
    
    printf("> ");
    scanf("%5s", input);
    
    printf("The input: %s\n", input);
    
    return 0;
}