編輯標題(我更改了標題,因為它錯誤地參考了宏和編譯時間,導致對我的問題感到困惑)
為了幫助我在 c 程式中輸出測驗,我在每次測驗之前列印測驗編號。像這樣的輸出:
[1/2] test :
// some test
[2/2] test :
// some test
測驗的計數分為兩部分:
[ <number of this test> / <total number of tests> ]
如果我添加或洗掉一個測驗,我不必硬寫<number of this test>,因為它是一個每次都會自增的 int 。但是,我必須<total number of test>手動計算并寫下來(例如,在宏中,但這也可能是一個變數)。
這是代碼的樣子:
#include <iostream>
#define N_TEST "2"
int main() {
int i = 0;
std::cout << "\n[" << i << "/" N_TEST "] test something :\n";
{
// some tests here
}
std::cout << "\n[" << i << "/" N_TEST "] test another thing :\n";
{
// some different tests here
}
return 0;
}
有沒有辦法<total number of tests>自動填充?
uj5u.com熱心網友回復:
目前尚不清楚您為什么要使用宏。如果可能,最好避免使用宏。正如評論中所建議的,您可以在容器中注冊測驗,一旦知道總共有多少測驗,您就可以將總數與正在運行的測驗編號一起列印:
#include <vector>
#include <functional>
#include <iostream>
int main(int argc, char *argv[])
{
std::vector<std::function<void()>> tests;
tests.push_back(
[](){
std::cout << "hello test\n";
}
);
tests.push_back(
[](){
std::cout << "hello another test.\n";
}
);
int counter = 0;
for (const auto& test : tests){
std::cout << counter << "/" << tests.size() << " ";
test();
}
}
輸出:
1/2 hello test
2/2 hello another test.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/436778.html
標籤:C
