You can't (in general). Once something is written to cout (standard out), you don't know what's been done with it.
On my Windows machine, your program prints "xyza".
However, if you redirect your program to a file (
), you'll get "ayz" as you intended.
It's finicky, and I wouldn't rely on such hackish stuff. Edit: Actually, since you're now effectively working with a file, it should follow standard file rules.
You can, however, write and manipulate output streams other than cout, e.g. a stringstream
https://en.cppreference.com/w/cpp/io/basic_ostream/seekp
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <sstream>
#include <iostream>
int main()
{
std::ostringstream os("hello, world");
os.seekp(7);
os << 'W';
os.seekp(0, std::ios_base::end);
os << '!';
os.seekp(0);
os << 'H';
std::cout << os.str() << '\n';
}
|
If you're talking about editing what was previously written to a
console or terminal, that becomes platform-specific and we're no longer just talking about C++ streams.
For very simple console manipulation, you can use \b ("backspace") to actually move the cursor to the left
1 2 3 4 5 6 7 8
|
#include <iostream>
using namespace std;
int main(){
cout << "xyz";
cout << "\b\b";
cout << 'a';
}
|
Will output
xaz
on a console (at least on Windows, I can't test *nix right now).
But if you run it through a web application or something else that might be redirecting standard out in a special way, something like that isn't guarenteed to work.
e.g. on cpp.sh, you'll get
xyza
.
This is also what you'll get if you redirect stdout to a file. It will literally write the 6 characters (x, y, z, backspace, backspace, a), in order, to a file.
And if you cat/type this file you created (e.g.
type file.txt), you'll get xaz printed to the console, because now you're once again having the console interpret \b as "move the cursor to the left".