0

The "vowels" function in this code is not taking inputs. But when I use the same concept of taking inputs used in the "vowels" function alone in a separate C program it works. The problem it is creating is that it is skipping the while loop of getchar() completely in the "vowels" function. Pls, help me solve it. The rest of the program is working fine.

#include <stdio.h>
#include <string.h>

void vowels(void);
void sum(void);

void vowels()
{
char str[100];
char ch;

int n = 0, i = 0, count = 0;

printf("Enter your string : ");

while ((ch = getchar()) != '\n')
{
    str[i++] = ch;
    n++;
}

str[i] = '\0';

printf("%s", str);

for (int i = 0; i <= n; i++)
{
    if (str[i] == 'a' || str[i] == 'A' || str[i] == 'e' || str[i] == 'E' || str[i] == 'i' || str[i] == 'I' || str[i] == 'o' || str[i] == 'O' || str[i] == 'u' || str[i] == 'U')
    {
        count++;
    }
}

printf("\n\nNumber of vowels : %d\n\n", count);
}

void sum()
{
int arr[10][10], r, c, sum = 0;

printf("\n\nEnter number of rows : ");
scanf("%d", &r);

printf("\nEnter number of columns : ");
scanf("%d", &c);

printf("\n\nEnter the values : ");
for (int i = 0; i < r; i++)
{
    for (int j = 0; j < c; j++)
    {
        scanf("%d", &arr[i][j]);
    }
}

// Summation

for (int i = 0; i < r; i++)
{
    for (int j = 0; j < c; j++)
    {
        sum = sum + arr[i][j];
    }
}

printf("\n\nSum of elements in the matrix is : %d\n\n", sum);
}

int main()
{
int n;

printf("\n\nEnter : \n1 --> To find the number of NumberOfVowels in a string\n2 --> To calculate sum of elements in a matrix");

printf("\n\nEnter Your Choice : ");
scanf("%d", &n);

switch (n)
{
case 1:
    vowels();
    break;

case 2:
    sum();
    break;

default:
    break;
}

return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
RM14
  • 11
  • 2
  • You have a home-made string input in `vowels()`, which follows `scanf()` in `main()`. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). Your input loop reads that newline and that's it: empty string. *Don't mix you input methods* unless you know their behaviour intimately. Aside: `char ch` should be `int ch`. Why? Have a look at [`getchar()`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/getchar-getwchar?view=msvc-170) closely and note that 'character' does not mean `char`. – Weather Vane Jan 28 '22 at 17:19
  • Call `getchar()` right before calling `vowels()`. The previous `scanf("%d", &n)` leaves the `\n` in the input stream and `getchar()` will absorb it. But be aware that `scanf` is not suited for user friendly input anyway. But admittedly the previous comment is better. – Jabberwocky Jan 28 '22 at 17:21

0 Answers0