前面学习了循环、判断常用的形式,现在来动手自己联系编写一下吧
练习的解决方案有很多种,如有错误,请多多指教。
1 运用for循环,完成数组倒序的访问
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main()
{
int Buffer[25] = { 0 };
int arrayindex = 0;
cout << "Please input the element "<<endl;
for (arrayindex = 0; arrayindex <= 4; ++arrayindex)
{
cout << "the element is " << arrayindex<<": ";
cin >> Buffer[arrayindex];
}
cout <<endl<< "invert of Buffer is : " << endl;
for (arrayindex = 4; arrayindex >=0; --arrayindex)
{
cout << "the element is " << arrayindex<<": ";
cout << Buffer[arrayindex]<<endl;
}
system("pause");
return 0;
}
另一种方法:
要注意循环的初值为:arrayindex = LineEnter.length()-1
原因是:标签比字符串的长度小1,区分上面直接使用数组标签的区别
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main()
{
char Buffer[20] = { '\0' };
cout << "Enter a line of text" << endl;
string LineEnter;
cin >> LineEnter;
if (LineEnter.length() < 20)
{
strcpy_s(Buffer, LineEnter.c_str());
cout << "Buffer is : " << Buffer << endl;
}
cout <<endl<< "invert of Buffer is : " << endl;
int arrayindex = 0;
for (arrayindex = LineEnter.length()-1; arrayindex >=0; --arrayindex)
{
cout << "the element is " << arrayindex<<": ";
cout << Buffer[arrayindex]<<endl;
}
system("pause");
return 0;
}
输出的结果如下图所示: