cin.get() 和 cin.getline() 的区别

difference between cin.get() and cin.getline()(cin.get() 和 cin.getline() 的区别)

本文介绍了cin.get() 和 cin.getline() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,对 C++ 中的 get()getline() 函数有一些疑问.

我对这两个函数的理解:

getline() 函数读取一整行,并使用回车键传输的换行符来标记输入的结束.get() 函数很像 getline(),但不是读取和丢弃换行符,get() 将该字符留在输入队列.

我正在阅读的这本书(C++ Primer Plus)建议使用 get() 而不是 getline().我的困惑是 getline() 并不比 get() 更安全,因为它确保以 ' ' 结束行.另一方面,get() 只会将字符挂在输入队列中,从而可能导致问题?

解决方案

优点和缺点数量相当,而且-基本上-都取决于您正在阅读的内容:get() 叶队列中的分隔符,从而让您能够将其视为下一个输入的一部分.getline() 丢弃它,所以下一个输入将在它之后.

如果您正在谈论来自控制台输入的换行符,丢弃它是完全合理的,但如果我们考虑来自文件的输入,您可以将下一个字段的开头用作分隔符".

什么是好"或安全",取决于你在做什么.

I am new to programming, and I have some questions on get() and getline() functions in C++.

My understanding for the two functions:

The getline() function reads a whole line, and using the newline character transmitted by the Enter key to mark the end of input. The get() function is much like getline() but rather than read and discard the newline character, get() leaves that character in the input queue.

The book(C++ Primer Plus) that I am reading is suggesting using get() over getline(). My confusion is that isn't getline() safer than get() since it makes sure to end line with ' '. On the other hand, get() will just hangs the character in the input queue, thus potentially causing problem?

解决方案

There are an equivalent number of advantages and drawbacks, and -essentially- all depends on what you are reading: get() leaves the delimiter in the queue thus letting you able to consider it as part of the next input. getline() discards it, so the next input will be just after it.

If you are talking about the newline character from a console input,it makes perfectly sense to discard it, but if we consider an input from a file, you can use as "delimiter" the beginning of the next field.

What is "good" or "safe" to do, depends on what you are doing.

这篇关于cin.get() 和 cin.getline() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:cin.get() 和 cin.getline() 的区别

基础教程推荐