16進数を10進数に変換(C/C++)

2177 ワード

タイトルの説明
16進数の数値文字列を受け入れ、その数値の10進数文字列を出力するプログラムを書きます.(複数組同時入力)
説明を入力:
16進数の数値文字列を入力します.
出力の説明:
数値の10進数文字列を出力します.
入力例:
0xA
出力例:10
方法1:進数間変換の関係を用いて,スタック出スタックを用いて処理し,比較的複雑であり,主な目的はデータ構造の知識を復習することである.
//          
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include

#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10

typedef char ElemType;
typedef struct//      
{
	ElemType *base;
	ElemType *top;
	int stackSize;
}sqStack;

void InitStack(sqStack *s)//    
{
	s->base = (ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
	if (!s->base)
	{
		exit(0);
	}
	s->top = s->base;
	s->stackSize = STACK_INIT_SIZE;
}

void Push(sqStack *s, ElemType e)//  
{
	if (s->top - s->base >= s->stackSize)
	{
		s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT)*sizeof(ElemType));
		if (!s->base)
		{
			exit(0);
		}
		s->top = s->base + s->stackSize;
		s->stackSize += STACKINCREMENT;
	}
	*(s->top) = e;
	s->top++;
}

void Pop(sqStack *s, ElemType *e)
{
	if (s->top == s->base)
	{
		return;
	}
	*e = *--(s->top);
}

int StackLen(sqStack s)//    ,      ,      
{
	return (s.top - s.base);//         
}

int main()
{
	ElemType c;
	while(scanf("%c", &c))
	{
		sqStack s;
		int len, i, sum = 0;

		InitStack(&s);
		//scanf("%c", &c);
		while (c != '
') { Push(&s, c); scanf("%c", &c); } len = StackLen(s); for (i = 0; i < len - 2; i++) { Pop(&s, &c); if (c >= 48 && c <= 57) c = c - 48; else if (c >= 65 && c <= 70) c = c - 55; else if (c >= 97 && c <= 102) c = c - 87; else printf("%s
", " "); sum = sum + c * pow(16, i); } printf("%d
", sum); } system("pause"); return 0; }

方法2:ネットで見たテクニックの1つで、入出力ストリームの方法を採用して、とても巧みです
#include
using namespace std;

int main()
{
    int a;
    while(cin>>hex>>a)
        cout<