栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

计算机程序设计c++ 8-6:数组指针相关应用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计算机程序设计c++ 8-6:数组指针相关应用

反序输出数组

  • 实现
#include
#include
using namespace std;

// 反序存放各数组元素
void invert(double *x, int n)
{
	double t, *i, *j;
	i = x;
	j = x + n -1;
	while(i 
字符串排序 

  • 实现
#include 
#include 

using namespace std;

void sort(char (*p)[10], int n)
{
	for(int i=0; i 0)
			{
				strcpy(t, p[i]);
				strcpy(p[i], p[j]);
				strcpy(p[j], t);
			}
		}
	}
}

int main()
{
	char str[][10] = {"zhang", "wang", "wen", "xu", "li", "zhou"};
	// char (*s)[10] = new char[n][10];  // 定义动态数组
	sort(str, 6);
	for(int i=0; i<6; i++)
	{
		cout << str[i] << "t";
	}
	return 0;
}

自己实现比较函数与复制函数,集成交换函数以及显示字符串

char *mystrcpy(char *s1, char *s2)  // copy s2 into s1
{
	while(*s2 != 0)
	{
		*s1++ = *s2++;
	}
	*s1 = '';
}

int mystrcmp(char *s1, char *s2)
{
	while(*s1 == *s2 && ! *s1!= 0 && *s2 != 0)
	{
		s1++;
		s2++;
	}
	return *s1 - *s2;  // 正值,前一个大,负值,后一个大
}

void swap(char *p, char *q)
{
	char t[10];
	mystrcpy(t, p);
	mystrcpy(p, q);
	mystrcpy(q, t);
}

void show(char (*s)[10], int n)
{
	for(int i=0; i 
二进制ip地址转化为点分十进制形式 

  • 实现:
    • 检测字符串中是否有01之外的字符
    • 二进制数 --> 十进制数
#include 
#include 

using namespace std;

// check only contain 0/1 in str
bool check(char *str)
{
	for(int i=0; i<32; i++)
	{
		if(str[i] != '1' && str[i] != '2')
		{
			return false;
		}
	}
	return true;
}


// 32位二进制数转化为十进制数
// 1101B = (((0*2+1)*2+1)*2+0)*2+1 = 13
int trans(char *Str)
{
	int n=0, i;
	for(i=0; i<8; i++)
	{
		if(str[i] =='1')
		{
			n = n*2 + 1;
		}
		else
		{
			n = n*2;
		}
	}
	return n;
}


int main()
{
	char IP[33];
	cout << "32位二进制IP地址?" << endl;
	cin >> IP;
	if(strlen(IP) != 32)
	{
		cout << "IP 长度应该是32位" << endl;
	}
	else
	{
		if(!check(IP))
		{
			cout << "字符串中有0/1之外的字符,非正确IP地址." << endl;
		}
		else
		{
			cout << "IP地址对应的点分十进制数写法:" << endl;
			cout << trans(IP) << "." << trans(IP+8) << "." << trans(IP+16) << "." << trans(IP+24) << endl;
		}
	}
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/510139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号