user3259411
user3259411

Reputation: 23

Printing multiple lines at the same time C++

#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
void slowPrint(unsigned long speed, const char *s)
{
   int i = 0;
   while(s[i]!=0)
   {
      cout << s[i++];
      cout.flush();
      Sleep(speed);
   }
}
int main()
{
      char choice;

      cout << "================================================================================\n";
      slowPrint(80, " \"Words being said\"\n\n");
      cout << "================================================================================\n";
      cin >> choice;

      return 0;
}

So I was wondering if I could somehow print line 19-21 at the same time. Instead of just having the first "===..." print out, then the slow typing from line 20, and lastly the end of the code.

Or is there a way to even output both of the "===" bars and then slow typing the line between them.

Please help if you can!

Thanks.

(You might be confused on how this is worded but it's hard to explain. I can try and explain more in depth if needed.)

Upvotes: 2

Views: 5878

Answers (1)

iamjboyd
iamjboyd

Reputation: 88

One way to print fancy things to a terminal screen is to use escape sequences. If you've ever wondered how your keyboard tells your computer about arrow key inputs, even though there are no explicit ASCII keys for those operations, escape sequences are the answer.

Escape sequences are begun with the escape character, or ASCII value 27. To move the cursor up, you need something along the following lines:

char esc(27); //You need to initialize the escape character by calling its ASCII value
std::cout << esc << "[1A" // This line moves the cursor up.
          << "\r"; // This line moves the cursor all the way back to the left.

So, in order to get the output you want, try the following for the body of your main:

char choice, esc(27);

std::cout << "================================================================================\n\n"
          << "================================================================================"
          << esc << "[1A\r";
slowPrint(1, " \"Words being said\"\n\n");
std::cin >> choice;

return 0;

There are many escape sequences that can be used to control your terminal. For instance, try printing the following escape sequence followed by some other text.

"[1;31m"

See the following link for more escape sequences.

http://ascii-table.com/ansi-escape-sequences.php

Upvotes: 2

Related Questions