C/C++如何在一行中按两次enter键或在两行换行后读取标准输入
我试图让用户向控制台输入一段文本,我的程序只有在连续两次按enter键,或者用另一种方式说,当在已经空白的行上按enter键时,才会从stdin中读取该文本。但是,我想继续从stdin中读取数据,所以基本上,只有在已经空行的情况下点击enter时才从stdin中读取数据。然后刷新并重新启动 用户输入示例:C/C++如何在一行中按两次enter键或在两行换行后读取标准输入,c++,c,input,stdin,C++,C,Input,Stdin,我试图让用户向控制台输入一段文本,我的程序只有在连续两次按enter键,或者用另一种方式说,当在已经空白的行上按enter键时,才会从stdin中读取该文本。但是,我想继续从stdin中读取数据,所以基本上,只有在已经空行的情况下点击enter时才从stdin中读取数据。然后刷新并重新启动 用户输入示例: Hello(\n) World(\n) (\n) (Read Now) 我还没有找到能够指定这种行为的输入函数 此外,我还尝试了一些使用单字符检索函数的方法,但未能使其正常工作 有人知道一种
Hello(\n)
World(\n)
(\n)
(Read Now)
我还没有找到能够指定这种行为的输入函数
此外,我还尝试了一些使用单字符检索函数的方法,但未能使其正常工作
有人知道一种优雅的方法吗
已落实的答复:
char word[100];
int i = 0;
while ((word[i++] = getchar())!='\n' || (word[i++]=getchar())!='\n');
printf("%s",word);
显然,在使用此方法之前需要处理缓冲区溢出。仅举一个例子。基本上,您希望忽略输入,直到序列\n\n。您可以通过以下方式完成:
while (getchar()!='\n' || getchar()!='\n');
//read the input now
忽略一切,直到你读到一个空白行,然后停止忽略
// Untested code
std::string s;
// Ignore first block
while(std::getline(std::cin, s) && !s.empty()) {
/* nothing */
;
}
// Don't ignore the second block
while(std::getline(std::cin, s)) {
std::cout << "You typed: " << s << "\n";
}
您可以创建一个过滤流缓冲区,该缓冲区在输入行时读取行,但在看到两个换行之前阻止转发字符。然后,它可以假装这就是预期的一切,直到有什么东西重置它。代码如下所示:
class blockbuf: public std::streambuf {
public:
blockbuf(std::streambuf* sbuf): sbuf_(sbuf), blocked_(false) {}
int underflow() {
std::istream in(this->blocked_? 0: this->sbuf);
for (std::string line; std::getline(in, line) && !line.empty(); ) {
this->buffer_ += line + "\n";
}
if (this->in_) {
this->buffer_ += "\n";
}
this->setg(this->buffer_.c_str(), this->buffer_.c_str(),
this->buffer_.c_str() + this->buffer_.size());
this->blocked_ = true;
return this->gptr() == this->egptr()
? traits_type::eof()
: traits_type::to_int_type(*this->gptr());
}
void unblock() { this->blocked_ = false; }
private:
std::streambuf* sbuf_;
bool blocked_;
std::string buffer_;
};
如果要通过std::cin使用此流缓冲区,可以使用std::cin.rdbuf替换std::cin的流缓冲区:
blockbuf b(std::cin.rdbuf());
std::istream in(&b);
for (std::string block; std::getline(in, block, 0); b.unblock(), in.clear()) {
processAllLinesUpToEmptyLine(block);
}
显然,如何玩这个游戏有很多不同的方法…当你读空行时,逐行阅读并设置一个标志。刷新和重新启动意味着什么?您指定的程序语义非常糟糕。美观、简短、简单。我想有一个比我想出的冗长的解决方案更好的方法。