Search code examples
cstringcs50character-limit

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


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.


Solution

  • 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);
    }