3

I'm having problems with how to show the numbers of vowels in the string I input in this code I made

#include <iostream>
#include<conio.h>
using namespace std;


int main()
{
   char str[100];
   int a, e, i, o, u, whitespace;
   a = e = i = o = u = whitespace = 0;
   int k;

   cout << "Enter a string: ";
   cin >> str[99];
        
   for (k = 0; k < strlen(str); k++)
   {
       if (str[k] == 'A')
       {
           a = a + 1;
       }
       else if (str[k] == 'E')
       {
           e = e + 1;
       }
       else if (str[k] == 'I')
       {
           i = i + 1;
       }
       else if (str[k] == 'O')
       {
           o = o + 1;
       }
       else if (str[k] == 'U')
       {
           u = u + 1;
       }
       else if (str[k] == ' ')
       {
           whitespace++;
       }
   }

   cout << "\nVowels:\n";
   cout << "A " << a;
   cout << "\nE " << e;
   cout << "\nI " << i;
   cout << "\nO " << o;
   cout << "\nU " << u;
   cout << "\nWhitespaces - " << whitespace;

    return 0;
}



I hope I just need to tweak a few things because I'm new to programming lol

I typed "WELCOME TO ARRAYS" but the vowels and whitespace shows 0

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
Mangoenoot
  • 33
  • 3
  • 1
    The `cin >> str[99];` is wrong as it reads in only one character into the arrays last element. Try `cin >> str;`. – Adrian Mole Jan 16 '23 at 13:45
  • `cin >> str[99];` reads 1 `char` and stores it in 99th position in your array; the rest of your array is uninitialized garbage. – pptaszni Jan 16 '23 at 13:45
  • Consider using `std::string str;` instead of a "C" style fixed size character array. And use str.size() to get its length. – Pepijn Kramer Jan 16 '23 at 14:02
  • Consider using `switch/case` statement instead of an `if-else-if` ladder. Also consider using a string search (have a string of vowels and search it). – Thomas Matthews Jan 16 '23 at 20:09

1 Answers1

2

The error is here

cin >> str[99];

You must write to the beginning of the array so just pass

cin >> str;

or if you want to be more clear pass the address of the first element

cin >> &str[0];

and str will be filled from the beginning ith the chars you enter.

The >> operator only reads until the first whitespace though, so it would only count vowels of the first word.

So in general cin.getline or std::getline is better as it reads everything

cin.getline(str,sizeof(str));
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98