循环问题。 Cin C++ getline 清除缓冲区

发布于 2024-09-27 16:56:44 字数 192 浏览 7 评论 0原文

我遇到了问题,但我无法弄清楚我做错了什么。我不确定这是我的循环的问题,还是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

a√萤火虫的光℡ 2024-10-04 16:56:44

问题出在您尝试清除缓冲区时。当您从 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.

屋檐 2024-10-04 16:56:44

你给 cin.getline 一个 12 长的缓冲区,所以它只需要那么多字符,其余的仍然在缓冲区中。如果您改为使用

 string str;
 cin.getline(str)

“Then”,您将获得整行,然后您可以将其裁剪为 11 个字符。不是 100% 符合 cin 语法,但你明白了。

或者移动上面的忽略部分

cin >>cont;

以这种方式忽略额外的字符。

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

 string str;
 cin.getline(str)

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

cin >>cont;

to ignore the extra characters that way.

愚人国度 2024-10-04 16:56:44
cin >> cont;
cout << "\n" << endl;
cin.ignore(200,'\n');

应该是

cin.ignore(200,'\n');
cin >> cont;
cout << "\n" << endl;
cin >> cont;
cout << "\n" << endl;
cin.ignore(200,'\n');

should be

cin.ignore(200,'\n');
cin >> cont;
cout << "\n" << endl;
甜中书 2024-10-04 16:56:44

您可以通过修改 cStringToUpper fn 来更正您的程序。像这样的东西:

...    
int loopCount;
char buffer[256];
cin.getline(buffer,256);
strncpy(letters, buffer, 11);
//letters[11]= '\0';
cout << "\n" << endl;
...

You may correct your program by modifying your cStringToUpper fn. something like:

...    
int loopCount;
char buffer[256];
cin.getline(buffer,256);
strncpy(letters, buffer, 11);
//letters[11]= '\0';
cout << "\n" << endl;
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文