Small Problem with a getline statement
I seem to be having a problem on a snippet of code in my program.
In this portion of the program I am looking to display the numbers of vowels from an entered string.
I am utilizing a getline for an entered string to accept spaces. However, whenever I would run the program the following is displayed:
Need a message: Message:
Number of Vowels: 0
Here is my code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int choice1(){
string str;
int v = 0;
cout<<"Need a Message: ";
getline(cin, str);
for (int i = 0; str[i] != '\0'; ++i)
{
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' || str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') ++v;
}
cout <<" Message: "<< str << endl;
cout <<"Number of Vowels: "<< v <<endl;
}
|
Some help would be appreciated.
It looks like you've some previous input using say cin >> var
Which has left a stray \n on the input stream.
So all your str contains here is a newline.
Look up cin.ignore().
When I would use cin.ignore, the code loops infinitely.
I think you'll find this works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <string>
int main(){
std::string str;
int v = 0;
std::cout<<"Need a Message: ";
std::getline(std::cin, str);
for (int i=0; i<=str.length(); ++i)
{
if (tolower(str[i]) == 'a' || tolower(str[i]) == 'e' || tolower(str[i]) == 'i' ||
tolower(str[i]) == 'o' || tolower(str[i]) == 'u') ++v;
}
std::cout << "Message: "<< str << std::endl;
std::cout << "Number of Vowels: "<< v << std::endl;
}
|
Sample Output:
Need a Message: This IS a Test
Message: This IS a Test
Number of Vowels: 4
|
Hope that helps.
Last edited on
Topic archived. No new replies allowed.