这道题写的比较乱,主要就是字符串处理问题,因为带有空白字符的一整行字符串无法用scanf读入,而部分OJ又禁用gets函数,所以在这里选择用cin.getline(),然后再分解字符串。
大致思路就是利用结构体数组,其中用0/1分别表示目录or文件,再另设置两个变量用于保存文件/目录名称及其所属目录路。最后根据读入的字符串判断对应操作即可,因为题目已经限制了很多极端条件,所以总体来说这道题只是写着麻烦,但并不难。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
struct File {
int sta; //0为目录, 1为文件
char name[100];
char fdir[100];
};
int main() {
int T;
scanf("%d", &T);
while (T > 0) {
int n, tot = 1;
scanf("%d\n", &n);
char str[5][109];
char ch[109];
File file[109];
file[0].sta = 0;
strcpy(file[0].name, "root"); //初始化root的目录信息
strcpy(file[0].fdir, "###");
for (int p = 0; p < n; p++) {
cin.getline(ch, 109, '\n');
int le = strlen(ch), h = 0, r = 0;
for (int i = 0; i < le; i++) { //将一行字符串分解
if (ch[i] != ' ')
str[h][r++] = ch[i];
else {
str[h][r] = '\0';
h++;
r = 0;
}
}
str[h][r] = '\0'; //想一下若没有这行代码会发生什么?
int len = strlen(str[0]); //四种字符串长度分别为7 8 9 10
int op = len % 7; //取模
if (op == 0) { //LISTDIR
for (int i = 0; i < tot; i++)
if (strcmp(file[i].fdir, str[1]) == 0 && file[i].sta == 0) printf("%s\n", file[i].name);
} else if (op == 1) { //LISTFILE
for (int i = 0; i < tot; i++)
if (strcmp(file[i].fdir, str[1]) == 0 && file[i].sta == 1) printf("%s\n", file[i].name);
} else if (op == 2) { //CREATEDIR
file[tot].sta = 0;
strcpy(file[tot].name, str[1]);
strcpy(file[tot].fdir, str[2]);
tot++;
} else if (op == 3) { //CREATEFILE
file[tot].sta = 1;
strcpy(file[tot].name, str[1]);
strcpy(file[tot].fdir, str[2]);
tot++;
}
}
T--;
}
return 0;
}