2015-03-13 51 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

相关问题