循环问题。 Cin C++ getline 清除缓冲区
我遇到了问题,但我无法弄清楚我做错了什么。我不确定这是我的循环的问题,还是 cin 缓冲区没有被清理。我正在做一个将 C 风格字符串转换为大写的程序,但是如果用户输入超过 11 个字符,那么该函数应该只显示前 11 个字符,而之后的任何内容都不应显示。问题是,如果我输入超过 11 个字符,那么我的循环永远不会停止,并不断告诉用户输入的答案无效以及他是否想输入新字符串。
I am having a problem, but I cannot figure out what I'm doing wrong. I'm not sure if it's a problem with my loop, or the cin buffer is not being cleaned. I am doing a program that transforms a C-style string to uppercase, however if the user enters more than 11 characters, then the function should only display the first 11, and anything after that should not be displayed.the problem is that if I enter more than 11 characters, then my loop never stops and keeps telling the user that the answer entered is invalid and if he would like to enter a new string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题出在您尝试清除缓冲区时。当您从 cStringToUpper 返回时,缓冲区中仍然有多余的字符,但您会立即查找 y/q。
The issue comes from when you're trying to clear your buffer. When you return from cStringToUpper there are still extra characters in your buffer, but you're immediately looking for y/q.
你给 cin.getline 一个 12 长的缓冲区,所以它只需要那么多字符,其余的仍然在缓冲区中。如果您改为使用
“Then”,您将获得整行,然后您可以将其裁剪为 11 个字符。不是 100% 符合 cin 语法,但你明白了。
或者移动上面的忽略部分
以这种方式忽略额外的字符。
You give cin.getline a buffer 12 long so it will only take that many characters, the rest are still in the buffer. If you instead use
Then you will get the whole line, then you can crop it at 11 characters. Not 100% on the cin-syntax but you get the idea.
Or move the ignore-part above
to ignore the extra characters that way.
应该是
should be
您可以通过修改 cStringToUpper fn 来更正您的程序。像这样的东西:
You may correct your program by modifying your cStringToUpper fn. something like: