编写代码,演示任意一个字符串从两端移动,向中间汇聚,并以这样的形式输出。
#include<windows.h>
Sleep(n毫秒)
延迟n毫秒再输出
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<Windows.h>
int main()
{
int i = 0;
printf( "输入字符的个数n:_" );
int n= 0;
scanf( "%d" ,&n);
char *p1 = (char *)malloc(n + 1);
char *p2 = (char *)malloc(n+ 1);
if (p1 == NULL || p2 == NULL)
{
printf( "out of memory\n" );
exit(1);
}
scanf( "%s" , p1);
int len = strlen(p1);
for (i = 0; i < len; i++)
{
p2[i] = '#' ;
}
p2[len] = '\0' ;
int left = 0;
int right =len-1;
printf( "%s\n" ,p2);
while (left <= right)
{
Sleep(1000); //睡上一秒,再输出
p2[left] = p1[left];
p2[right] = p1[right];
printf( "%s\n" ,p2);
left++;
right--;
}
free(p1);
free(p2);
system( "pause" );
return 0;
}
或者:
int main()
{
int i = 0;
char p1[100];
char p2[100];
scanf( "%s" , p1);
int len = strlen(p1);
for (i = 0; i < len; i++)
{
p2[i] = '#' ;
}
p2[len] = '\0' ;
int left = 0;
int right = len - 1;
printf( "%s\n" , p2);
while (left <= right)
{
Sleep(1000);
p2[left] = p1[left];
p2[right] = p1[right];
printf( "%s\n" , p2);
left++;
right--;
}
system( "pause" );
return 0;
}
试分析两个代码对内存的利用率。
模拟三次密码登录:初始密码123456
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i = 0;
char arr[10];
while (i < 3)
{
gets(arr);
if (strcmp(arr,"123456" )== 0)
{
printf( "登录成功\n" );
system( "pause");
return 0;
}
i++;
printf( "登录失败\n" );
}
printf( "已经用完三次机会了\n" );
system( "pause");
return 0;
}