您試過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