I had created a program that counts the amount of vowels in a provided string. It counts the vowels correctly and repeats when the user provides a 'y' or 'Y'. However, when it repeats, it automatically assigns "" to the C-string I am attempting to use.
int main()
{
//Creating repeating decision
char answer = 'y';
while ((answer == 'y') || (answer == 'Y'))
{
//declaring our C-String
char ourString[81] = "Default";
//Prompting user for a string, storing it as a C-String
std::cout << "Please enter a string!(Less than 80 characters please.)\n";
std::cin.getline(ourString, 81);
//Using a loop to count the amount of vowels
int ourNum = 0;
int vowels = 0;
while (ourString[ourNum] != '\0')
{
switch (ourString[ourNum]) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
case 'y':
case 'Y':
vowels++;
ourNum++;
break;
default:
ourNum++;
break;
}
}
std::cout << "The numbers of vowels in: \"" << ourString << "\" is " << vowels << "!\n";
std::cout << "Do again? Please enter \"Y\" to repeat, or any other character to escape.";
std::cin >> answer;
}
}
Any direction would be appreciated. Thanks!
After writing "y" and hitting the enter button both the "y" and the "/n"
are stored in the input buffer, so the "y" goes to the answer char, and "/n" is considered the input of the next getline.
There are a few solutions to this. You could add a call to cin.ignore()
after cin >> yes
. Or you could make yes a string, and use getline
instead of operator>>
there.