2016-09-20 26 views
-5

如何使用宏而不是函數提取包含在另一個號碼中的號碼。提取號碼

示例僞代碼:

#define extract_number(int number, // original number 
        int pos, // start position from behind (1 == first digit) 
        int len) // count of digits 
{ 
    ... 
} 

main() { 
    int number = 0; 
    int result = 0; 

    number = 123456789; 
    result = extract_number(number, 2, 3); // result: 678 

    number = 987123456; 
    result = extract_number(number, 4, 4); // result: 7123 
} 

編輯2016年9月21日: 我要做的ATM如下:

int number = 123456789; 
int result = number/10 % 1000; 

使用張貼@Frzn FLMS功能的版本是這樣的我會已經在一個函數中完成了它。有沒有辦法在編譯時使用宏來完成它?

+4

我投票結束這個問題作爲題外話,因爲它顯然是寫我的代碼請求,而不是問題。請先閱讀[問]頁面。 :) –

+0

到目前爲止請顯示您的研究/調試工作。請先閱讀[問]頁面。 –

+0

你的意思是找到那個數字的主要因素? – Olaf

回答

0

例如:2應該由10被替換和3應由1000

代替它使用升壓如下被寫入。

#include <stdio.h> 
#include <boost/preprocessor/control/while.hpp> 
#include <boost/preprocessor/arithmetic/add.hpp> 
#include <boost/preprocessor/tuple/elem.hpp> 
#include <boost/preprocessor/cat.hpp> 

#define PRED(d, state) BOOST_PP_TUPLE_ELEM(2, 0, state) 

#define OP(d, state) (BOOST_PP_DEC(BOOST_PP_TUPLE_ELEM(2, 0, state)), BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 1, state), 0)) 

#define pow0(n) BOOST_PP_TUPLE_ELEM(2, 1, BOOST_PP_WHILE(PRED, OP, (BOOST_PP_ADD(n,1), 1))) 

int main(void) { 
    int n = pow0(2);//1000: "1" + "0"✕(n+1) 
    printf("%d\n", n); 
    return 0; 
}