字符串拷贝(Pending)
YOYO
posted @ 2009年10月26日 19:31
in 【ICPC】解题报告
with tags
模拟
, 2488 阅读
前几天写DBOp的时候,同桌告诉俺用strcpy_s会比较安全,瞬间想起了当年校赛的这题。。于是挑战之~
虽然oj上是wa的(题目要求变量可定义于任何位置,这段代码只考虑变量定义于strcpy之前 如果想AC请自己注意这点^^),但是。。额觉得额比较符合常理。。 遂贴出纪念:
其实只有五种语句(函数名,{,},char,strcpy),对其分别进行处理即可~(我只会模拟啊模拟 = =)
题目要求有变量作用域,因此用了个栈来存储,为了判断变量是否在当前作用域,存储类型是一对pair<int,string>,int存当前{个数,string存size大小~如果遇到},则当前layer=pair.first的栈顶都出栈~
-
#include <iostream>
-
#include <map>
-
#include <stack>
-
#include <string>
-
using namespace std;
-
-
typedef pair<int, string> SIZE_PAR;
-
typedef stack<SIZE_PAR> SIZE_STK;
-
typedef map<string, SIZE_STK> VARSIZE_MAP;
-
-
string getVarName(char* pszLine, int* pnSizePos = NULL)
-
{
-
char szName[100];
-
int i = 0;
-
while (pszLine[i] != '[' && pszLine[i] != ',') {
-
szName[i] = pszLine[i];
-
++i;
-
}
-
szName[i] = '\0';
-
-
if (NULL != pnSizePos)
-
{
-
*pnSizePos = i + 1;
-
}
-
-
return string(szName);
-
}
-
-
string getVarSize(char* pszLine)
-
{
-
char szName[100];
-
int i = 0;
-
while (pszLine[i] != ']')
-
{
-
szName[i] = pszLine[i];
-
++i;
-
}
-
szName[i] = '\0';
-
return string(szName);
-
}
-
-
int main(void)
-
{
-
VARSIZE_MAP mapVarSize;
-
int nLayer = 0;
-
-
char szLine[100];
-
int nSizePos;
-
-
string strVarName;
-
string strVarSize;
-
-
int t, i;
-
char* p;
-
-
while (gets(szLine))
-
{
-
p = szLine;
-
while (strstr(p, "{") != NULL)
-
{
-
++p;
-
++nLayer;
-
}
-
-
p = szLine;
-
while (strstr(p, "}") != NULL)
-
{
-
for (VARSIZE_MAP::iterator mpit = mapVarSize.begin(); mpit != mapVarSize.end(); ++mpit)
-
{
-
while (!mpit->second.empty())
-
{
-
if (mpit->second.top().first != nLayer) break;
-
mpit->second.pop();
-
}
-
}
-
-
++p;
-
--nLayer;
-
}
-
-
// strcpy to strcpy_s
-
p = strstr(szLine, "strcpy(");
-
if (p != NULL)
-
{
-
t = p - szLine;
-
-
strVarName = getVarName(p + 7);
-
-
strVarSize = mapVarSize[strVarName].top().second;
-
-
for (i = 0; i < t; ++i)
-
{
-
putchar(szLine[i]);
-
}
-
-
if (strstr(szLine, "\"\"") == NULL)
-
{
-
printf("strncpy(%s, %s, """, strVarName.c_str(), strVarSize.c_str());
-
p = strstr(szLine, ", ");
-
-
i = 2;
-
while (p[i] != ')')
-
{
-
putchar(p[i]);
-
++i;
-
}
-
-
printf(""");\n");
-
-
for (i = 0; i < t; ++i)
-
{
-
putchar(szLine[i]);
-
}
-
-
if (strVarSize[0] >= '0' && strVarSize[0] <= '9')
-
{
-
nSizePos = atoi(strVarSize.c_str());
-
printf("%s[%d] = 0;\n", strVarName.c_str(), nSizePos - 1);
-
}
-
else
-
{
-
printf("%s[%s - 1] = 0;\n", strVarName.c_str(), strVarSize.c_str());
-
}
-
}
-
else
-
{
-
printf("%s[0] = 0;\n", strVarName.c_str());
-
}
-
-
continue;
-
}
-
-
// get vars' name and size
-
p = strstr(szLine, "char ");
-
if (p != NULL)
-
{
-
strVarName = getVarName(p + 5, &nSizePos);
-
-
if (mapVarSize.find(strVarName) == mapVarSize.end())
-
{
-
mapVarSize[strVarName] = *new SIZE_STK;
-
}
-
-
mapVarSize[strVarName].push(make_pair(nLayer, getVarSize(p + 5 + nSizePos)));
-
}
-
-
// puts normal
-
puts(szLine);
-
}
-
-
return 0;
-
}