《C++程序与设计》WORK TWELVE
作者声明:文章代码有借鉴各位前辈之处,如需声明,还请联系作者(忘记借鉴哪位前辈的代码了。。)
T 1
//使用指针作为函数参数编写程序,对输入的两个整数按从大到小的顺序输出,
//子函数的作用是利用指针实现两数交换
#include <iostream>
using namespace std;
int main ()
{
int *p1 , *p2;
int a , b;
cout << "请输入两个整数:\n";
cin >> a >> b;
p1 = &a , p2 = &b;
int temp;
if (*p1 < *p2)
{
temp = *p1;
*p1 = *p2;
*p2 = temp;
};
//cout << *p1 <<" "<< *p2 << endl;
cout << a << " " << b << endl;
system ("pause");
}
T 2
//使用指针作为函数编写程序,对输入的三个整数按从大到小顺序输出,
//子函数的作用是利用指针实现两数交换
#include <iostream>
using namespace std;
int main ()
{
void exchange (int *p1 , int *p2);
int a , b , c;
cout << "请分别输入三个整数: \n";
cin >> a >> b >> c;
if (a < b) exchange (&a , &b);
if (b < c) exchange (&b , &c);
if (a < b) exchange (&a , &b);
cout << a << ' ' << b << ' ' << c << endl;
system ("pause");
}
void exchange (int *p1 , int *p2)
{
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
T 3
//写一个函数,求一个字符串的长度。
//在 main 函数中输入字符串,并输出其长度。
#include <iostream>
#define N 100
using namespace std;
int main ()
{
char array [N] = { };
char c;
int i;
int figure = 0;
for (i = 0; (c = getchar()) != '\n'; i ++)
{
array [i] = c;
}
char *p = array;
while (*p != '\0')
{
p ++;
figure ++;
}
cout << figure <<endl;
system ("pause");
}
T 4
//利用指针编写函数,输入一行字符串,找出其中的大写字母、小写字母、空格、数字以及其他字符各有多少。
#include <iostream>
#define N 100
using namespace std;
int main ()
{
char array [N] = { };
char c;
int i;
int space = 0;
int captial = 0;
int lower = 0;
int figure = 0;
int others = 0;
char *p = array;
for ( i = 0;(c = getchar ()) != '\n'; )
{
array [i ++] = c;
}
for (i = 0; *p != '\0' ; i ++) //指针遍历法
{
if (*p == ' ')
{
p ++;
space ++;
}
else if (*p >= 'A' && *p <= 'Z')
{
p ++;
captial ++;
}
else if (*p >= 'a' && *p <= 'z')
{
p ++;
lower ++;
}
else if (*p >= '0' && *p <= '9')
{
p ++;
figure ++;
}
else
{
p ++;
others ++;
}
}
cout << "空格的数量为 :\t" << space
<< "\n大写英文字母的数量为 :\t" << captial
<< "\n小写英文字母的数量为 :\t" << lower
<< "\n数字的数量为 : \t" << figure
<< "\n其他字符的数量为 :\t" << others << endl;
system ("pause");
}
T 5
//有一个字符串,包含 n 个字符。
//写一函数,将此字符串从第 m 个字符开始的全部字符复制成为另一个字符串。
#include <iostream>
#define N 100
using namespace std;
int main ()
{
char array [N] = { };
char brray [N] = { };
char c;
int i = 0;
int location = 0;
char *p1 = &array[0]; //将数组 array 的首地址作为指针变量 p1 的初值
//p1 = &array[0]; 亦可以写成这样的形式
char *p2 = &brray[0];
//p2 = &brray[0];
while ( (*p1 = getchar ()) != '\n') p1 ++; //当没有空格输入时, p1 ++
while ( (*p2 = getchar ()) != '\n') p2 ++;
cout << "请您输入您想将字符串 brray 复制到字符串 array 的位置: \n";
cin >> location;
p1 = &array[location - 1];
p2 = &brray[0];
for ( ; *p2 != '\0' ; p1 ++ , p2 ++)
{
*p1 = *p2;
}
*p1 = '\0';
//cout << array << "\n" << brray << endl; //用于检验程序的正确性
//cout << *p1 << *p2 << endl;
cout << array << endl;
keep_window_open ();
}