说我有一个命令行程序。当我说
时,有没有办法呢?std::cout << stuff
如果我不在另一个std::cout << '\n'
之间执行std::cout << stuff
,则另一个输出的内容将覆盖从最左边的列开始的同一行(清理行)上的最后一个内容?
我认为ncurses有能力这样做吗?如果可能的话,如果我能说std::cout << std::overwrite << stuff
其中std::overwrite
是某种iomanip。
答案 0 :(得分:4)
您是否尝试过回车\r
?这应该做你想要的。
答案 1 :(得分:1)
还值得查看转义字符文档:http://en.wikipedia.org/wiki/ANSI_escape_code
除了将carret设置回到行开始位置之外,你可以做更多的事情!
答案 2 :(得分: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
OverWrite()函数清除以前的东西&#34;并将光标放在它的开始处。
如果您想要清理整行并在其中打印new_stuff 那么只需要使
OverWrite()
的论点足够大OverWrite(100)
或类似的东西来清理整条线 共
如果你不想清理任何东西,只需从头开始更换,你就可以这样做:
#include<iostream>
#define overwrite "\r"
int main(){
std::cout<<"stuff"<<overwrite<<"new_stuff";
return(0);
}
答案 3 :(得分: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
那么容易,但我希望它有所帮助。