【问题标题】:Converting from base 10 to any base between 2 and 36从基数 10 转换为 2 到 36 之间的任何基数
【发布时间】:2017-02-09 17:28:34
【问题描述】:

我正在编写一个 C++ 代码,它将无符号的以 10 为基数的整数转换为 2 到 36 之间的任何其他基数。我有一段时间没有编写代码了,所以我正在重新学习所有内容。我的问题是:我怎样才能将它保留为 printf,最后没有 cout,并且仍然显示 ascii 值。是否有可能让它变得简单(基本)。对不起,如果我没有正确格式化。

#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;
}

【问题讨论】:

  • 参见web.archive.org/web/20150204050528/http://www.jb.man.ac.uk/… 了解itoa(非标准通用函数)的内部结构。哦等等,移动版还在上线,strudel.org.uk/itoa
  • 你为什么要使用硬编码的 ascii 值,例如 48 而不是 '0'?你把它标记为 C++ 那么你为什么关心 printf 和 scanf 呢?学习使用 cin 和 cout。
  • 我们的教授希望我们熟悉 printf 和 scanf。
  • 我修复了 kfsone 提到的 ascii 问题。我仍然需要解决 cout 问题...
  • @noobisko cout 问题究竟是什么?你必须用printf()替换它?`

标签: c++ ascii converter base


【解决方案1】:

为了输出带有printfstd::string,您必须将其作为以空字符结尾的字符串(C 样式字符串)提供给printf。或者,好吧,您并非绝对必须:您可以一次打印一个字符。但是将它作为一个以空字符结尾的字符串是最简单和实用的。

您可以通过.c_str() 成员函数做到这一点,因此:

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

请注意,由于动态分配,在这种低级别使用 std::string 可能会很昂贵。例如,(http://www.strudel.org.uk/itoa/),对itoa 的各种实现进行计时,发现了 40 倍的惩罚。

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多