2013-04-14 111 views
0

在这里呆了几个小时,无法弄清楚如何以我想要的方式得到这个。将光标定位在屏幕上

我需要它在中心这样的控制台输出文本...

******************************************* 
      ABC Industries 
       Report 
******************************************* 

,而不是其走出这样的..

********************************** 
ABC Industries 
Report 
    ********************************** 

这是我走到这一步,任何帮助将很乐意欣赏。

#include <string> 
#include <iomanip> 
#include <iostream> 
#include <windows.h> 
#include <cctype> 
using namespace std; 

class Heading 
{ 
private: 
    string companyName; 
    string reportName; 
public: 
    Heading(); 
    void placeCursor(HANDLE, int, int); 
    void printStars(int); 
    void getData(HANDLE, Heading&); 
    void displayReport(HANDLE, Heading); 
}; 

int main() 
{ 
    Heading display; 
    HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE); 
    display.getData(screen, display); 
    display.displayReport(screen, display); 
    cin.get(); 
    return 0; 
} 

Heading::Heading() 
{ 
    companyName = "ABC Industries"; 
    reportName = "Report"; 
} 

void Heading::placeCursor(HANDLE screen, int row, int col) 
{ 
    COORD position; 
    position.Y = row; 
    position.X = col; 
    SetConsoleCursorPosition(screen, position); 
} 

void Heading::printStars(int n) 
{ 
    for(int star=1; star<=n; star++) 
     cout << '*'; 
    cout <<endl; 
} 

void Heading:: getData(HANDLE screen, Heading &input) 
{ 
    string str; 
    placeCursor(screen, 2, 5); 
    cout <<"Enter company name"; 
    placeCursor(screen, 2, 26); 
    getline(cin, str); 

    if(str!="") 
     input.companyName = str; 
    placeCursor(screen, 4, 5); 
    cout<<"enter report name"; 
    placeCursor(screen, 4, 26); 
    getline(cin, str); 
    if(str!="") 
     input.reportName = str; 
} 

void Heading::displayReport(HANDLE screen, Heading input) 
{ 
    int l; 
    placeCursor(screen, 8, 5); 
    printStars(69); 
    string str=input.companyName; 
    l= str.length(); 
    l=39-l/2; 
    placeCursor(screen, 9, 1); 
    cout << str; 
    str=input.reportName; 
    l=str.length(); 
    l=39-l/2; 
    placeCursor(screen, 10, 1); 
    cout << str; 
    placeCursor(screen, 11, 5); 
    printStars(69); 
} 
+0

'的std :: setw'不工作了你(或重复空格)?设置光标位置似乎有点不必要,但我想你不能说控制台在标准C++中有多宽。 – chris

+0

请注意,您如何将文本定位在您的预期输出中。您只需事先输入足够的空格。 –

回答

0

你会踢自己。在标题

声明:: displayReport,你计算的公司名称的长度,那么你除以2,并从39减去你然后去将光标定位到9,1(九,一)。

你的意思是将光标位置设置为9,l(九,el)。

然后,您也重复监视reportName字段。 ;-p

因此,使这些2更改

// placeCursor(screen, 9, 1); 
    placeCursor(screen, 9, l); 

// placeCursor(screen, 10, 1); 
    placeCursor(screen, 10, l);