0

Just a question, is there anyway that I can have an input with a text already written for me with using "cin." I'm looking for a predefined function or whatever that I can use to have inputs with a text in it. My purpose of that is that I'm trying to make a simple text editor in command-line. Even if there aren't any predefined functions, anyone have a pseudocode to copy a string of words into a cin (or any other input). I hope that my question is not vague pointless.

Regards.

John Doe
  • 30
  • 6

1 Answers1

0

You can assign the buffer of std::cin to read from a file on disk instead of the terminal, like this:

ifstream file("file.txt");
cin.rdbuf(file.rdbuf());

From then on, when you read from cin it will give you the contents of file.txt.

If you prefer you can also make std::cin produce text directly from a string, like this:

istringstream stream("blah\nblah blah");
cin.rdbuf(stream.rdbuf());

Now when you read from cin you will get two lines: blah and blah blah.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • But, if I got the text from another source, can I still add, delete, or modify the already written text, or the stream will be restricted to "stream"? (hopefully you understand what I mean by that). – John Doe Jan 21 '15 at 05:16
  • No I don't understand what you're asking now. – John Zwinck Jan 21 '15 at 05:17
  • Like, for example, my text editor has two main purposes: make a new file, and modify an existing one. For modifying an existing one, I can copy what ever in the text file in an std::string, and then play with it. When it comes for editing by a user, what I need is that the user will have an input stream (say "cin"), but the space provided for writing stuff in the user input space will not be empty, but it will have text instead. This will make the user able to play with his/her text using cin input. In the next comment I'll give an example illustrate what I want. – John Doe Jan 21 '15 at 05:27
  • For example: user have a text file like this: "Hello, world!"; Then, the user will have an input that is not empty space for writing, but has "Hello, world!" and user can play with that text and write something like "Hello, to stackoverflow!" and then end the user input by typing something like ctrl + d. – John Doe Jan 21 '15 at 05:28
  • You cannot make a text editor in the modern sense using just `std::cin`. You need something richer, like `ncurses` to display "windows" on the screen and manipulate the contents beyond the current line. – John Zwinck Jan 21 '15 at 05:30
  • If you are saying that editors cannot have a traditional type of input, then how nano text editor is made?? – John Doe Jan 21 '15 at 05:32
  • If you want to make an editor similar to `nano`, you should use `ncurses`. On my system, `nano` in fact does use `ncurses` (you can see this by running `ldd $(which nano)`). – John Zwinck Jan 21 '15 at 05:34