2015-03-13 100 views
2

說我有一個命令行程序。有沒有辦法這樣,當我說輸出字符串用C++覆蓋終端上的最後一個字符串

std::cout << stuff 

,如果我不這樣做在另一std::cout << stuff之間的std::cout << '\n',東西另一個輸出將覆蓋在同一行的最後一個東西(清潔線)起始於最左邊一列?

我認爲有能力做到這一點嗎?如果可能的話,如果我可以說std::cout << std::overwrite << stuff

其中std::overwrite是某種iomanip。

回答

3

您是否試過回車\r?這應該做你想做的。

+1

不要忘了,包括以後的'的std :: flush' '\ r',否則你可能會寫很多很長時間沒有出現的「東西」,因爲iostream正在緩存它。 (例如'std :: cout << stuff <<'\ r'<< std :: flush;') – Malvineous 2015-03-14 11:04:54

0

您試過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一樣容易,但我希望它能幫助。

1

如果你只是想覆蓋的最後的東西印刷等在同一行上保持不變,那麼你可以做這樣的事情:

#include <iostream> 
#include <string> 

std::string OverWrite(int x) { 
    std::string s=""; 
    for(int i=0;i<x;i++){s+="\b \b";} 
    return s;} 

int main(){ 
    std::cout<<"Lot's of "; 
    std::cout<<"stuff"<<OverWrite(5)<<"new_stuff"; //5 is the length of "stuff" 
    return(0); 
} 

輸出:

Lot's of new_stuff 

覆寫( )函數清除之前的「stuff」,並將光標置於其開始處。

如果要被清洗的整條生產線和印刷new_stuff在 地方,那只是使OverWrite()大的說法不夠像 OverWrite(100)或類似的東西來清潔整條生產線總共 。

如果你不想清理東西,從一開始就只需更換,那麼你可以簡單地這樣做:

#include<iostream> 

#define overwrite "\r" 

int main(){ 
    std::cout<<"stuff"<<overwrite<<"new_stuff"; 
    return(0); 
} 
+0

想要解釋你的解決方案嗎? – 2015-03-15 10:58:46

+0

現在好嗎......? – Jahid 2015-03-15 20:28:29

+1

豎起大拇指!完美的解釋,優雅的解決方 – 2015-03-15 20:30:32

相關問題