echo a number with functions

This is a very noob question,i don't understand that why my getline inside the if statement doesn't executes. Can someone point out the problem.

#include<iostream>
#include<string>
#include<conio.h>

using namespace std;

int echoNum (string myString = "please provide me a number(this is by default)\n");

int main()
{
int num;
char ch;


cout<<"do you wanna enter the string or not (y/n)\n ";
cin>>ch;
if(ch=='y')
{
string mystring;
cout<<"please enter the string \n";
getline(cin,mystring);

num=echoNum(mystring);
cout<<"this was the number : "<<num<<endl;
}


else
{

num=echoNum();
cout<<"this was the number : "<<num<<endl;
}

getch();
}

int echoNum(string myString)
{
int num;
cout<<myString<<endl;
cin>>num;
return(num);
}
It does execute, but when you say cin >> ch, ch contains only the character/text entered before hitting enter (which causes ch to store that value). The newline character represented by hitting enter is still in the cin stream, and getline sees this as the next available "line", thereby storing no text in mystring. To fix this, before you use getline, insert cin.ignore(80, '\n');, which ignores the last 80 characters in the stream, stopping at the most recent newline character. This should solve your problem.
(Since you're only asking for one character - 'y' - you probably don't need to ignore 80 characters, but picking a higher number than necessary is always safe.)

Don't worry about it being a noob question - it's one that I'm sure every programmer has had at one point.
Because when you do std::cin >> ch; you enter letter and press "Enter" which inserts newline symbol. Extraction operator get character and leave newline in input buffer. Then getline takes all symbols until it will encounter newline, which is immideatly. So it never need your input actually because it founds everything in buffer.

You should skip that symbol if you want getline to work.
1
2
3
#include <limits>
/*...*/
std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
thanks a lot for all your replies. I guess, i have a lot to learn. :)
Topic archived. No new replies allowed.