是否可以将头文件设置为居中文本? - 在控制台中

时间:2017-12-31 21:20:31

标签: c++

我试图在函数中居中文本,但在名为center.h的头文件中定义函数

center.h:

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

void centerStr(string* str) {
    int consoleWidth = 80;
    cout << setw(consoleWidth / 2) << " " << str << endl;
}

main.cpp中:

#include <iostream>
#include <iomanip>
#include "center.h"

using namespace std;
int main() {
    system("clear");
    cout << centerStr("Unit Converter By DualKeys") << endl << 
    endl;
    return 0;
}

在main.cpp中,我不断收到错误说&#34;没有匹配函数来调用centerStr&#34;

[编辑]是的, 尝试在 main.cpp 文件中定义centerStr

1 个答案:

答案 0 :(得分:0)

在我看来,无论如何,这是一种令人难以置信的凌乱方式。 我会避免放......

using namespace std;

在任何头文件中或根本不保持代码清洁。

center.h

//declaration
void centerStr(const char*);

center.CPP

#include "center.h"
#include <iomanip>
#include <iostream>

//definition
void centerStr(const char* str) {
    int consoleWidth = 80;
    std::cout << std::setw(consoleWidth / 2) << " " << str << std::endl;
}

的main.cpp

#include "center.h"

int main() {
    centerStr("Unit Converter By DualKeys");
    system("PAUSE");
    return 0;
}

您需要为此函数的std :: string版本重载,否则函数模板就足够了。

template<typename T>
void centerStr(const T& t) {
    int consoleWidth = 80;
    std::cout << std::setw(consoleWidth / 2) << " " << t << std::endl;
}

最后只需将consoleWidth声明为全局const变量。在每次通话中看起来都很浪费! :)