输出字符串使用 C++ 覆盖 Linux 终端上的最后一个字符串

output string overwrite last string on terminal in Linux with c++

本文关键字:字符串 终端 最后一个 Linux 覆盖 C++ 输出      更新时间:2023-10-16

假设我有一个命令行程序。有没有办法,当我说

std::cout << stuff

如果我不在另一个std::cout << stuff之间做std::cout << 'n',另一个东西的输出会覆盖从最左边的列开始的同一行(清理行)上的最后一个东西?

我认为诅咒有能力做到这一点?如果可能的话,如果我能说std::cout << std::overwrite << stuff那就太好

std::overwrite是某种iomanip。

您是否尝试过回车r?这应该做你想要的。

还值得一看的是转义字符文档: http://en.wikipedia.org/wiki/ANSI_escape_code

您可以做的不仅仅是将 carret 设置回行起始位置!

如果你只想覆盖最后打印的内容,而同一行上的其他内容保持不变,那么你可以做这样的事情:

#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() 函数清理以前的"东西"并将光标放在它的开头。

如果您希望清洁整行并打印new_stuff 然后只是让OverWrite()足够大的论点像 OverWrite(100)或类似的东西来清洁整条生产线 完全。

如果您不想清洁任何东西,只需从头开始更换,然后您可以简单地这样做:

#include<iostream>
#define overwrite "r"
int main(){ 
    std::cout<<"stuff"<<overwrite<<"new_stuff";
    return(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);
}

关键部分是我们将输入到流中的字符附加到临时变量中,如果未读取"",则数据将被压缩。

用法:

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 returnn");
    good >> test;
    std::cout << test << std::endl;

}

这不会像iomanip那么容易,但我希望它有所帮助。