+ 1

help me on this code:

i have used the cin.getline function , this code recieves two marks and two names of students and show students with marks, but in the output won't give you the right output. and if you put cin.getline function before the other "for" loops it recieve true lnput and true output(names and then marks) i wanna know whats the procedure of cin.getline function: #include<iostream> #include<cstring> int main() { std::cout<<"enter your names"<<std::endl; char p[2][10]; int m[2]; for(int i=0;i<2;i++) std::cin>>m[i]; for(int n=0;n<2;n++) std::cin.getline(p[n],10); for(int j=0;j<2;j++) std::cout<<p[j]<<" "<<m[j]<<std::endl; } https://code.sololearn.com/cxot02Qnrh86/?ref=app

9th May 2022, 4:38 PM
Nariman Tajari
Nariman Tajari - avatar
3 Réponses
+ 1
cin reads just a word of input. Stops reading when space encounters or new encounters.. Leaves next for next input read. But getline reads entire line till new line encounters.. So 1 2 n1 n2 Will be fine input there after 2, space +n1 will be read by getline. If you input n1 in next line then only space will be read as name1 Put a getchar() after first looploop to consume \n character. Hope it helps..
9th May 2022, 4:48 PM
Jayakrishna 🇮🇳
+ 1
but when i enter 1 2 a b i recieve an strang output would you help me why i recieve strange output like this. 1 a 2
9th May 2022, 9:27 PM
Nariman Tajari
Nariman Tajari - avatar
+ 1
cin does not advances to next line after reading like getline method. After reading 2, console pointer still in 2nd and next getline reads the \n so 'a' will be read by getline into p[1] 'b' never going read by any. Add a getchar() after a first for loop and see... 'a' will read into p[0] and 'b' into p[1] Hope it helps..
9th May 2022, 9:34 PM
Jayakrishna 🇮🇳