You are not logged in.
good morning all,
i have a problem ...
i tried those ....
cin = my_string123 ;
and
cin << my_string123
that dont work ... i want to write text from a string into the cin-buffer ... can you say me many ways, how i can do that pleass?
Offline
You can’t write into `::std::cin` and all suggestions you may find telling you, that you can, are wrong.⁽¹⁾
It’s not just about a feature not being available, but the mere idea making no sense given what `::std::cin` models.
`::std::cin` represents the standard input.⁽²⁾ From within the program you only consume it. You don’t control it. Save both yourself and users of your program pain, by not trying to circumvent that model.
What is your actual goal? What are you trying to achieve? This looks like a typical XY problem.
If you want to generate data to pass to standard input, just pass the data while invoking your program. With bash:
$ yourprogram <data.file
$ sourceprogram | yourprogram
$ yourprogram << 'EOF'
multiline
data
using
heredoc
EOF
If you wish to generate some data and pass it to a method that accepts an `::std::istream`, you may use `::std::istringstream` (a `char` version of basic_istringstream) instead.
#include <iostream>
#include <istream>
#include <sstream>
#include <cstdlib>
using ::std::istream;
using ::std::istringstream;
using ::std::cout;
// NOTE: this function is meant to show the use of `istringstream` below.
// It should not be used in production, and in particular it doesn’t handle
// text properly.
static void printWidened(istream& input)
{
char cc = input.get();
while (input)
{
cout << cc;
if ('\n' != cc && '\r' != cc)
{
cout << ' ';
}
cc = input.get();
}
}
int main()
{
istringstream data("Hello world!");
printWidened(data);
return EXIT_SUCCESS;
}
____
⁽¹⁾ Of course you can always “hack around,” just like it is with a ton of nonsense “clear cin buffer” advices on the internet. There is no technical way that could stop you from breaking things and making them behave according to your expectations. At least until you discover they actually don’t, or everything falls apart after the next library or compiler update.
⁽²⁾ And it represents it with no connection to how a particular system implements the standard input. So you can’t assume `::std::cin` has the same properties as POSIX standard input. You can sync it with stdio, making most of the promises hold, but — again — only on POSIX-ish platforms.
Last edited by mpan (2025-06-11 12:27:06)
Sometimes I seem a bit harsh — don’t get offended too easily!
Offline
ok thanks for answer ...
can i use the method "get" on a string instead of "cin.get" ?
i had error messages, when i write ...
mystring123.get()
Offline
No, strings are not streams.
You still didn’t answer the question:
What is your actual goal? What are you trying to achieve? This looks like a typical XY problem.
Sometimes I seem a bit harsh — don’t get offended too easily!
Offline