作者:nd子听雨 | 来源:互联网 | 2023-10-13 16:29
reference:Problemwithgetline()aftercin-GeeksforGeeksAComputerScienceportalforgeeks.Itcon
reference :
> - GeeksforGeeks">Problem with getline() after cin >> - GeeksforGeeksA Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.https://www.geeksforgeeks.org/problem-with-getline-after-cin/The reasons:
The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.
意思是Cin这个函数在调用的时候,会给你的输入自动加一个空格,
而getline()这个函数如果读入的第一个字符是空格,它就默认你的输入结束了
对应的解决方案
The solution to solve the above problem is to use something which extracts all white space characters after cin. std::ws in C++ to do the same thing. This is actually used with the “>>” operator on input streams.
我自己问题的解决方案,是改换他们的位置:
# include
# include
# include
using namespace std;
int main()
{
// Initialize the variables including the number of students and biscuits
cout <<"Number of biscuits" < string fullName;
cout <<"Type your full name: ";
getline (cin, fullName);
cout <<"Your name is: " < int n = 0;
cin >> n;
}
也就是先做getline()然后在世cin这样就不会有问题了
挺有意思的,和大家分享