Search code examples
cfunctionprintfgets

GETS - C is not working for me


I am having trouble with inserting string in to char variable. Problem appeares when I put it into function. When I debug my program, it displays printf but it skipes gets

here is my code:

int uloz(SPRAVA *p){

    char string[200];

    printf("Your message here: ");
    gets(string);
    printf("You have entered: %s", string);
    getchar();

    return 0;
}

Solution

  • Use scanf(" %30[^\n]%*c",string);

    1. [^\n] will accept anything till \n.
    2. 30 will limit the length of number of characters to max 30.
    3. initial space(' ') will consume any \n already in stdin stream. (optional & i have not verified it)
    4. & Finally, %*c will consume \n pressed after entering string.

    I think, scanf(" %30[^\n]%*[^\n]%*c",string); would be a good option, to discard remaining characters (after 30) that were entered. However this is completely unverified. Just added as a possible idea. Test before use. :-)