一个好玩的现象:getline() cannot be used after Cin directly
2021/10/27 23:09:56
本文主要是介绍一个好玩的现象:getline() cannot be used after Cin directly,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
reference :
> - GeeksforGeeks" href="https://www.geeksforgeeks.org/problem-with-getline-after-cin/" rel="external nofollow" target="_blank">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 <iostream> # include <iomanip> # include <string> using namespace std; int main() { // Initialize the variables including the number of students and biscuits cout << "Number of biscuits" << endl; string fullName; cout << "Type your full name: "; getline (cin, fullName); cout << "Your name is: " << fullName; int n = 0; cin >> n; }
也就是先做getline()然后在世cin这样就不会有问题了
挺有意思的,和大家分享
这篇关于一个好玩的现象:getline() cannot be used after Cin directly的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-08测试人员在 Scrum 中的角色是什么?
- 2024-07-07Dify + TiDB Vector,快速构建你的AI Agent
- 2024-07-06有没有什么开源的py项目可以对图像进行分类-icode9专业技术文章分享
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享