getline problem

say i will input 5 sepate strings.
then the program outputs, "input string 1: input string 2:"
why 2 at the same time?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>   
#include <string>  
using namespace std;

int main () 
{	
	int n;
	cout << "input number of strings: ";
	cin >> n;
	string s1[100], s2;
	
	for(int i=0; i<n; i++){
		cin.clear();
		cout << "input string " << i+1 <<": ";		
		
		getline(cin,s1[i]);
		s2 += s1[i];
	}
	
	cout << "all strings: \n";
	cout << s2;	
}
Last edited on
Probably because of the dangling new line character left in the buffer by your previous extraction. Try to ignore() the character before you enter the loop.
Just to clarify a bit on what @jlb said. If you first use cin >> and then switch to getline(). You will have to put a cin.ignore(); after the cin >> (becuase of the reasons @jlb stated above). Like this -

1
2
3
4
5
int n;
	cout << "input number of strings: ";
	cin >> n;
	cin.ignore();
	string s1[100], s2;
Last edited on
thanks, cin.ignore(); worked.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>   
#include <string>  
using namespace std;

int main () 
{	
	int n;
	cout << "input number of strings: ";
	cin >> n;
	cin.ignore();
	string s1[100], s2;
	
	for(int i=0; i<n; i++){
		//cin.clear();
		cout << "input string " << i+1 <<": ";		
		
		getline(cin,s1[i]);
		s2 += s1[i];
	}
	
	cout << "all strings: \n";
	cout << s2;	
	
}
Topic archived. No new replies allowed.