getline(cin,string obj); problem....

Using Linux g++;


sample code as follows :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include<iostream>
#include<string>
using namespace std;
int main(){
	string str[5];
	
	int oo;
	cout<<"\ninput o: ";
	cin >> oo;
	cout<<"\n";
	
	for(int i=0;i<5;i++){
		getline(cin,str[i]);
	}
	for(int i=0;i<5;i++){
		cout<<"\nline no: "<<i<<" : "<<str[i];
	}
	cout<<"\n";
}


Program is supposed to read 5 lines from console and print them back.
Problem here is if a int type variable is before that it skips 1st line and
on console gives only 4 lines 1st line is blank....

similarly, i designed classes as
class String[user defined class overloading all need operators]
class Person[inherits from String for variables like name ID etc]
for :
1
2
3
4
5
6
7
8
9
10
void String::setString(){
     getline(cin,strObj);
     //strObj is 'String' mem Variable;
}


void Person::setPersonDetails(){
      name.setString();
      id.setString();
}



Then in main function
1
2
3
4
5
int main(){
   Person perObj[5];
   for(int i=0;i<5;i++)
      perObj[i].setPersonDetails();
}


Here in this case getline() used in setString() of String class does not work at all! I know flush() must be used, but then there is no flush in G++ linux.
need solution......!


Last edited on
flush() is for ostreams, for istreams you have sync()
if i've understood your problem correctly then use endl after cout and you will start to see your output on console.

cout<<"\nline no: "<<i<<" : "<<str[i] << endl;
Topic archived. No new replies allowed.