读书人

求教中科院的上机题2,该如何解决

发布时间: 2012-04-23 13:17:38 作者: rapoo

求教中科院的上机题2
现列出第二个题,希望大牛给出解答:
c/c++不限

有一个给一个数字字符串,从中截取一个长度为五位的最大的数

[解决办法]
我理解的是5个连续的数字,下面可在VC下执行
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
string strInput = "";
while(1) //循环输入
{
cout << "请输入字符串, 退出输入Exit:"; //提示输入字符串
cin >> strInput;
if (strInput == "Exit")
{
break;
}
if (strInput.size() < 5) //输入长度小于5时,提醒
{
cout << "输入字符串长度应该大于等于5"<<endl;
continue;
}
string::const_iterator iterBegin = strInput.begin(); //用一对迭代器表示5为字符
string::const_iterator iterEnd = iterBegin;
for (int i=0; i<5; i++) iterEnd++; //strEnd指向最后一位

string strTemp; //用于保存临时的5为字符
int nTemp; //用于保存临时数
int nMaxNum = 0;
while (1)
{
strTemp.assign(iterBegin, iterEnd); //赋予临时的5为字符串
nTemp = atoi(strTemp.c_str());
nMaxNum = nMaxNum > nTemp ? nMaxNum : nTemp; //去最大
if (iterEnd == strInput.end()) //已经到达字符串末尾,退出循环
{
break;
}
iterBegin ++; //向前移位
iterEnd ++;
}
cout << "最大五位数为:"<< nMaxNum <<endl;
}

return 0;
}

读书人网 >C语言

热点推荐