Problem with getline

I have a problem with my code. I was writing a code to encrypt N number of sentences and when i enter the number of cases the program skip the next line (just like if i would have pressed "enter" twice)

Here is the code:
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <string>
#include <conio.h>

using namespace std;

void terceiro(string &palavra)
{
	int size, p, Rec;
	size=(palavra.length())/2;
	for(p=size;p<palavra.length();p++)
	{
		Rec=((int)palavra[p])-1;
		palavra[p]=(char)Rec;
	}
	cout<<palavra<<endl;
}
void segundo(string &palavra)
{
	string palavrasub, palavrasub2;
	
	for(int j=palavra.length();j>=0;j--)
	{
		palavrasub=palavra[j];
		palavrasub2=palavrasub2+palavrasub;
	}
	palavrasub2.erase(0,1);
	palavra=palavrasub2;
	terceiro(palavra);	
}

void primeiro(string &palavra)
{
	int Rec;
	for(int i=0;i<palavra.length();i++)
	{
		if( ((int)palavra[i]>=65 && (int)palavra[i]<=90) || ((int)palavra[i]>=97 && (int)palavra[i]<=122))
		{
			Rec=(int)palavra[i]+3;
			palavra[i]=(char)Rec;
			
		}
	}
	segundo(palavra);
}
int main ()
{
	int N, i;
	cin>>N;
	
	string palavra;
	do{
		getline(cin, palavra);
		primeiro(palavra);
		N--;
	}while(N>=0);
}
This is a very frequent problem.

cin>>N; the >> operator here will ignore leading whitespace. When it finds a non-whitespace character, it begins reading characters which form part of a valid integer. As soon as a non-numeric character is found, whether it be a space or a newline or maybe a letter of the alphabet, the extracting of characters stops.

Hence after that operation there will be at least a newline and possibly some other characters as well, remaining in the input buffer.

On the other hand, getline doesn't ignore whitespace. It reads characters from the input buffer until the delimiting newline is found, then it stops.

In order to remove the unwanted characters from the input buffer, do something like this:
1
2
    cin>>N;
    cin.ignore(100, '\n');  // ignore up to 100 characters, or until '\n' is found. 




It worked, thank you
Topic archived. No new replies allowed.