您试过std::istream::sentry
吗?你可以尝试类似下面的内容,这会“审核”你的输入。
std::istream& operator>>(std::istream& is, std::string& input) {
std::istream::sentry s(is);
if(s) {
// use a temporary string to append the characters to so that
// if a `\n` isn't in the input the string is not read
std::string tmp;
while(is.good()) {
char c = is.get();
if(c == '\n') {
is.getloc();
// if a '\n' is found the data is appended to the string
input += tmp;
break;
} else {
is.getloc();
tmp += c;
}
}
}
return(is);
}
的关键部分是,我们输入到流中的字符附加到一个临时变量,并且如果“\ n”为未读出,数据被卡住。
用法:
int main() {
std::stringstream bad("this has no return");
std::string test;
bad >> test;
std::cout << test << std::endl; // will not output data
std::stringstream good("this does have a return\n");
good >> test;
std::cout << test << std::endl;
}
这会不会是相当作为iomanip
一样容易,但我希望它能帮助。
不要忘了,包括以后的'的std :: flush' '\ r',否则你可能会写很多很长时间没有出现的“东西”,因为iostream正在缓存它。 (例如'std :: cout << stuff <<'\ r'<< std :: flush;') – Malvineous 2015-03-14 11:04:54