when i use the code below, i never have an opportunity to enter the second string,
i know that the problem is related with null character remaining in the buffer.
but whats the exact story?
because when i use cin>>str2 instead of getline(cin,str2), there isnt any problem. why?
#include <iostream>
#include <string>
int main()
{
string str1,str2;
cout<<"enter 1st string: ";
cin>>str1;
cout<<"enter 2nd string: ";
getline(cin,str2);
//cin>>str2;
cout<<"\n1st string is: "<<str1<<endl;
cout<<"2nd string is: "<<str2<<endl;
return 0;
}
The problem is because the extraction operator (<<) skips all leading whitespace characters (spaces, newling character, tab character etc.), and then stops at the next whitespace character and leaves it in the istream (cin)
So when you use cin << and enter the word "hello" you when you hit the [enter] key you also put a newline character in the istream. that newline character stays there. Now if you use cin << again, it skips that newline character so there's no problem.
But the getline function simply reads all characters until it finds the newline character. So the cin << leaves a newline character ('\n') and then getline sees that and thinks it's done.
When I found this problem I wrote a function of my own that handles this, It is used exactly as getline, and uses the same parameters:
- void getlineNew(istream& inPut, string& line)
-
{
-
char ch;
-
-
ch = inPut.peek();//checks what the next character is.
-
if (ch == '\n') //if it's the newline character it
-
inPut.get(ch);//reads it so that getline doesn't
-
//get confused by a leftover newline char
-
-
getline(inPut, line);
-
}//end getlineNew
This function checks what the next character is first, if it's a newline character it throws it away. Then it calls getline using the same parameters you passed to it.