0

i am having a very weird problem in my code. after every time my program uses scanf to get a value for a char variable, it messes up everything that happens next and skips the gets(menu) in the beginning of the loop. it doesn't happen when the scanf is not used. any thoughts?

void main()
{
    char menu[20] = { 0 }, ch, ch2 = 0, str[SIZE] = { 0 }, str2[SIZE] = { 0 }, mat[SIZE][SIZE] = { 0 };
    int boo = 1, loop = 0, num;
    while (loop == 0)
    {
        printMenu();
        gets(menu);
        num = menuNum(menu);
        switch (num)
        {
        case 0:
            loop = 100;
            break;
        case 1:
            boo = 1;
            printf("Please enter a long string\n");
            gets(str);
            printf("Please choose separation character\n");
            scanf("%c", &ch);
            createMat(str, ch, mat);
            break;
        case 2:
            if (mat[0][0] == '\0')
                printf("Matrix does not exist!\n");
            else
            {
                printMatrix(mat);
            }
            break;
        case 3:
            boo = longShort(mat);
            break;
        case 4:
            printf("Please enter a long string\n");
            gets(str2);
            printf("Please choose separation character\n");
            scanf("%c", &ch);
            compareMat(str2, ch2, mat);
            break;
        default:
            printf("Not a valid option!\n");
        }
    }
}
llllllllll
  • 16,169
  • 4
  • 31
  • 54
sn123
  • 1

1 Answers1

0

scanf("%c", &c); read a single byte from the input stream and leaves the rest of the input pending, hence the next gets will read the pending newline and fail to wait for user input.

You can fix your code easily:

  • NEVER use gets because this function is unsafe and has been removed frm the C Standard, use fgets() insead.
  • use fgets() to read the user input into an array and use the first character of that array as your char value.

The difference between gets() and fgets() is you provide the size of the destination array to fgets(), which prevents overlong input from causing chaos. Note however that the trailing newline '\n' will be present at the end of the array, before the null terminator, if the array is large enough and the newline is indeed present in the input stream before the end of file. You will need to handle it yourself, either ignoring it or removing it.

chqrlie
  • 131,814
  • 10
  • 121
  • 189