我使用getline ( cin.getline() one)从cin中获取一个字符串,并找到一个特殊情况下的问题。如果用户输入的字符多于流参数(在本例中为50),cin缓冲区将保存这些字符,并将它们放入下一个cin调用中。如果我使用cin.clear()和cin.ignore(),并且用户输入的字符少于streamsize参数,那么程序等待用户再次按enter才能继续。因此,我使用strlen来检查字符串的大小,如果字符串有50个字符,则只使用cin.clear()和cin.ignore()。这将删除用户在第49字符之后输入的额外字符。问题是,当用户输入准确的49个字符时,缓冲区中就没有额外的字符可以用cin.clear()和cin.ignore()调用来截断,因此程序将坐下来等待用户再次按enter键。
以下是几个问题:
1)是否有一个标志,我可以检查,看看缓冲区中是否有字符,只有当这个标志为真时,我才能清除()和忽略()?
2)还有其他方法可以调用这个getline函数,它在streamsize参数之后切断所有字符吗?
这是我的代码:
#include <iostream>
#include <cstring>
using namespace std;
#define SIZE 50
void getString(char*);
int main() {
char words[SIZE];
getString(words);
return 0;
}
void getString(char* words) {
cout << "Enter your string: ";
cin.getline(words, SIZE);
if (strlen(words) == SIZE - 1) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}将导致此问题的示例49个字符输入:
abcdefghijklmnopqrstuvwxysabcdefghijklmnopqrstuvw删除或添加一个字母,以查看程序的正常性能。
发布于 2018-07-06 19:57:50
您可以使用istream::gcount()来判断行中是否还有除'\n'以外的其他字符。
这是你需要考虑的案件。
cin.gcount()的返回值小于SIZE-1。在这种情况下,这一行什么都没有了。你不用担心会忽略剩下的部分。cin.gcount()的返回值为SIZE-1。这可能是由于两种情况造成的。1. The user enters `SIZE-2` characters followed by a newline. In this case, there is nothing left in the line. You don't have to worry about ignoring the rest of the line.
2. The user enters `SIZE` or more number of characters followed by a newline. In this case, there are still some characters left in the line. You will want to ignore the rest of the line.
cin.gcount()的返回值为SIZE。只有当用户输入SIZE-1字符后加上换行符时,才会发生这种情况。行中的所有字符都被读入函数提供的参数中。换行符将被读取和丢弃。你不用担心会忽略剩下的部分。给出上述情况,您唯一需要担心的是忽略行的其余部分时,您会遇到case 2.2。当cin.gcount() == SIZE-1和strlen(words) == SIZE-1满足这个条件时。
void getString(char* words) {
cout << "Enter your string: ";
cin.getline(words, SIZE);
if (cin.gcount() == SIZE-1 && strlen(words) == SIZE-1)
{
// There are characters in the stream before the \n.
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}https://stackoverflow.com/questions/51216733
复制相似问题