functions calling

i was wondering for hours, why it always skip the input when i call the function vowels? any help would be much appreciated .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include<iostream>
#include<string>

void vowels();
using namespace std;

int main()
{
	int choice;
	cout<<"Enter choice: ";
	cin>>choice;
	
	if(choice==1){
		vowels();
	}
}

void vowels(){
	string str1;
	int vowels=0;
	
	cout<<"Enter strings: ";
	getline(cin,str1);
	
	for(int i=0;i<str1.length();i++)
	{
		
		if((str1[i]=='a' || (str1[i]=='e')) || (str1[i]=='i') || (str1[i]=='o') || (str1[i]=='u'))
		{
			vowels=vowels+1; //vowels++;
		}
		
	}
	
	cout<<vowels;
}
closed account (SECMoG1T)
add any of this to line 21

1
2
3
4
5
std::cin.ignore(10000,'\n');

//or

std::cin.ignore(std::numeric_limits<std::streamsize>::max());
thank you guys for the reply and it works. im having difficulties understanding why it needs this kind of code cin.ignore(10000,'\n')? is this common problem when calling a function with a string? thanks again.
The data is read from a buffer.

The buffer contains some data, and at the end of that data is a newline character.

cin>>choice;
User enters 1 and presses ENTER, buffer looks like this:

<1> <NEWLINE>

The <1> is taken out. Buffer looks like this:

<NEWLINE>

getline(cin,str1);

getline reads from the buffer as far as <NEWLINE>. Where is the <NEWLINE>? At the front of the buffer. So getline reads nothing, and the program carries on.

cin.ignore fetches characters from the buffer and throws them away. You need to throw away that <NEWLINE> at the front of the buffer.

std::cin.ignore(10000,'\n'); means "throw away characters from the buffer until you've thrown away 10000, or until you've thrown away a NEWLINE.

std::cin.ignore(std::numeric_limits<std::streamsize>::max()); means "throw away characters from the buffer until you've thrown away some really big number of them.





Last edited on
thank you all again and god bless.
Topic archived. No new replies allowed.