0

I have some code that takes in a paragraph and starts a new line after every sentence.

I would like to buffer the output in the terminal with a new line, but adding "std::cout << endl;" outside of the loop does not seem to work. Any help in separating the input from the output if it is typed into a terminal.

I have commented out the code I expected to work, but which does not.

#include <iostream>
#include <string>
using namespace std;

int main() {

  // std::cout << std::endl;

  for (;;) {
    string line;
    getline(std::cin, line);
    if (!cin) {
      break;
    }
    for (unsigned int i = 0; i < line.length(); ++i) {
      const string text = line.substr(i, 1);
      if (text == "." || text == "?" || text == "!") {
          std::cout << text;
          std::cout << std::endl;
      }else{
          std::cout << text;
      }
    }
  }

  // std::cout << std::endl;

  return 0;
}
Vyff
  • 83
  • 6
  • Possible duplicate of [Flushing of cout prior to reading input using cin .. why?](http://stackoverflow.com/questions/2704752/flushing-of-cout-prior-to-reading-input-using-cin-why) – Barmar Jan 19 '17 at 00:18
  • I tried to flush "cout" with a type before each new push of a new line, but that doesn't seem to allow a new line to be created first still. – Vyff Jan 19 '17 at 00:34
  • @CodingPig is almost right. If you want an extra line before input, I think all you need to do is move the commented-out line up one brace. – user4581301 Jan 19 '17 at 00:35
  • While that works, then it is in the loop and executes before every sentence but I only want it before the paragraph. – Vyff Jan 19 '17 at 00:39
  • I recommend learning to use the debugging software that almost certainly came with your debugger. With it you can control the execution of your code, slowing down to line by line if you want to so you can watch the program run and see what it does. You can inspect the variables as well. Very handy. – user4581301 Jan 19 '17 at 00:39
  • Then you need to find a way to signal a new paragraph that isn't a newline and exit the loop when you find one. Right now the only way out of the loop is to end the console's input. Can't do much after that unless you start the console back up again. – user4581301 Jan 19 '17 at 00:41
  • Or can you...? Huh. Never tried. – user4581301 Jan 19 '17 at 00:42
  • 1
    Maybe we don't understand the question. I thought you were trying to *prevent* output from being flushed until you read a whole sentence. – Barmar Jan 19 '17 at 00:43
  • I made a for loop for the first iteration to add a new line and made the rest covered in its conditions, its inelegant but works for now. – Vyff Jan 19 '17 at 00:54

1 Answers1

-1

The commented line will never work since it will never be called. You have an endless loop for(;;) before it.

Coding Pig
  • 66
  • 5