2016-10-01 77 views
-2

之間我正在寫一個C++代碼,一個無符號的基座10的整數轉換爲2和36之間的任何其它鹼我還沒有在一段時間編碼,所以我種重新學習一切。我的問題是:我怎麼能保持它只是printf,最後沒有cout,並仍然顯示ascii值。是否有可能使其變得簡單(基本)。如果我沒有正確格式化,很抱歉。從基座10轉換到任何基材2和36

#include <iostream> 
#include <stdlib.h> 
#include <stdio.h> 
#include <string> 
using namespace std; 

int main() 
{ 
    int InitialNum, BaseNum, Num, x; 
    string FinalNum, Temp; 

    printf("Enter an unsigned integer of base ten: \n");//Prompt user for  input 
    scanf_s("%d", &InitialNum); 
    printf("Enter the base you want to convert to (min2, max36): \n"); 
    scanf_s("%d", &BaseNum);    
    x = InitialNum; //save the base 10 number to display at the end 


    while (InitialNum != 0) //continue dividing until original input is 0 
    {    
     Num = InitialNum % BaseNum; //save remainder to Num       
     int ascii = 48; //declare conversion variable (from int to char)    
     for (int i = 0; i < 32; ++i)//for loop converts Num from int 0-15 to char '0'-'9', 'A'-'F' 
     { 
      if(Num == i) 
      Temp = ascii;     
      ascii += 1;         
      if (ascii == 58)//skip from 9 to A on the ascii table and continue 
      ascii = 65; 
     }       
     FinalNum = Temp + FinalNum;//add to the final answer(additions to the left)      
     InitialNum /= BaseNum; //the initial base10 number gets divided by the base and saved as the quotient    
    }   
    printf("The number %d converted to base %d is:", x, BaseNum); 
    cout<<(FinalNum); 
    system("PAUSE"); 
    return 0; 
} 
+0

請參閱http://web.archive.org/web/20150204050528/http://www.jb.man.ac.uk/~slowe/cpp/itoa.html以獲得對itoa內臟的良好闡述'(一個非標準的通用功能)。哦,等待,移動的版本仍然在線,在http://www.strudel.org.uk/itoa/ –

+2

爲什麼你使用像'48'這樣的硬編碼ascii值而不是放置''0'?你把它標記爲C++,那麼你爲什麼關心printf和scanf呢?學習使用cin和cout。 – kfsone

+0

我們的教授希望我們熟悉printf和scanf。 – noobisko

回答

0

爲了輸出與printf一個std::string你必須把它用來printf作爲空終止字符串中,C風格的字符串。或者,你不是絕對到:你可以一次打印一個字符。但將它作爲一個以空字符結尾的字符串來處理是最容易和最實用的。

你可以做到這一點通過.c_str()成員函數,因此:

printf("%s\n", FinalString.c_str()); 

注意,使用std::string可以在東西這種低水平是昂貴的,由於動態分配(一個或多個)。例如,(http://www.strudel.org.uk/itoa/),定時itoa的各種實現,發現40倍懲罰。