这道题有坑!!!
输入描述说命令与参数之间用一个空格隔开,但实际上样例中它们不是用空格隔开的!
命令与参数之间的空白是一个编码为-15712的不可见字符,如果用读单词的方式读入命令和参数的话,会把一整行字符串都读进来,导致程序出错。这个bug我找了至少四个小时,用单步调试都没看出来!
如果正常写程序的话,很可能会发现样例过不了。但本题的评测数据中还是用空格分隔命令和参数的,所以就算样例没过,也是能AC本题的。要注意一下格式错误,样例中对空目录使用ls命令没有输出,但实际上需要输出一个空行
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <list>
struct file {
std::string _name;
bool _is_dir;
file * parent;
std::list<file *> _sub_file;
file(std::string name, bool is_dir) {
_name = name;
_is_dir = is_dir;
parent = nullptr;
}
~file() {
std::list<file *>::iterator it;
for (it = _sub_file.begin(); it != _sub_file.end(); it++) {
delete *it;
*it=nullptr;
}
}
void create_file(std::string name, bool is_dir) {
file * new_file = new file(name, is_dir);
if (is_dir) {
new_file->parent = this;
}
_sub_file.push_back(new_file);
}
void get_list() {
if (_sub_file.size() == 0) {
std::cout << std::endl;
return;
}
std::list<file *>::iterator it;
for (it = _sub_file.begin(); it != _sub_file.end(); it++) {
std::cout << (*it)->_name;
if (++it != _sub_file.end()) {
std::cout << " ";
}
--it;
}
std::cout << std::endl;
}
};
struct System {
file * root;
file * cur;
std::vector<std::string> path;
System() {
root = new file("", true);
path.push_back(root->_name);
cur = root;
}
~System() {
delete root;
root=nullptr;
}
bool execute(std::string command) {
std::istringstream in(command);
std::string instruction;
std::string argument;
in >> instruction;
if (instruction == "ls") {
cur->get_list();
} else if (instruction == "pwd") {
get_path();
} else if (instruction == "exit") {
return false;
} else if (instruction == "touch") {
in >> argument;
cur->create_file(argument, false);
} else if (instruction == "mkdir") {
in >> argument;
cur->create_file(argument, true);
} else if (instruction == "cd") {
in >> argument;
if (argument == "..") {
if (cur->parent != nullptr) {
cur = cur->parent;
path.pop_back();
}
} else {
size_t i;
std::list<file *>::iterator it;
for (it = cur->_sub_file.begin(); it != cur->_sub_file.end(); it++) {
if ((*it)->_name == argument) {
break;
}
}
cur = *it;
path.push_back((*it)->_name);
}
}
else if (instruction == "echo") {
std::getline(in, argument);
if (argument != "") {
argument = argument.substr(2,argument.size()-3);
}
std::cout << argument << std::endl;
}
else if (instruction == "rm") {
in >> argument;
std::list<file *>::iterator it;
for (it = cur->_sub_file.begin(); it != cur->_sub_file.end(); it++) {
if ((*it)->_name == argument) {
break;
}
}
cur->_sub_file.erase(it);
}
return true;
}
void get_path() {
std::cout << "/";
for (size_t i = 1; i < path.size() - 1; i++) {
std::cout << path[i] << "/";
}
std::cout << path[path.size() - 1];
std::cout << std::endl;
}
};
int main() {
System system;
std::string cmd;
while (std::getline(std::cin, cmd)) {
if (!system.execute(cmd)) {
break;
}
}
return 0;
}