1. 程式人生 > >將字串陣列以16進位制的形式輸出

將字串陣列以16進位制的形式輸出

下面的程式主要是將字串的陣列,以16進位制的形式輸出,用空格隔開。

#define _CRT_SECURE_NO_WARNINGS
#include <fstream>  

#include <string>    
#include <sstream>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
	char *temp = new char[8];
	temp[0] = 01;
	temp[1] = 2;
	temp[2] = 03;
	temp[3] = 10;
	temp[4] = 11;
	temp[5] = 7;
	temp[6] = 9;
	std::stringstream  ss;
	for (int i = 0; i<7; i++)
	{
		
		int tm = temp[i];
		ss << std::hex << std::setw(2) << std::setfill('0') << tm;//見下文註釋
		ss << " ";
	}
	string c = ss.str();
	string d;
	transform(c.begin(), c.end(), back_inserter(d), ::toupper);//將小寫轉化為大寫
	std::cout << "string is : " << d << std::endl;
	system("pause");
	return 0;

}

ss << std::hex << std::setw(2) << std::setfill('0') << tm。這裡的stringstream  ss;定義的字串流,是將後面的字串按照物件存入到ss中並以空格鍵結束,如01為一個物件,02為一個物件,物件之間都有空格。std::hex表示16進位制輸出流,即後面輸出的為16進位制的形式,setw(2)以兩個字元的形式輸出,setfill(0)不夠兩個字元的用0填充。最後的輸出結果為: