我在使用 std::string::find() 时遇到麻烦。我通过以下代码从控制台读取字符串:
50 while(command.find(exitString) != 0) {
51 std::cout << "$ ";
52 getline(std::cin, command);
53
54 doSwitch(command);
55 }
然后我通过以下函数“切换”它们:
59 void Console::doSwitch(std::string command) {
60 if(command.find(helpString) == 0) {
61 help();
62 } else if(command.find(loadString) == 0) {
63 try {
64 doLoad(command);
65 } catch(std::string str) {
66 std::cout << str << std::endl;
67 }
68 } else if(command.find(dumpProcString) == 0) {
69 try {
70 doDumpProc(command);
71 } catch(std::string str) {
72 std::cout << str << std::endl;
73 }
74 } else if(command.find(dumpMemString) == 0) {
75 doDumpMem();
76 } else if(command.find(defmemString) == 0) {
77 try {
78 doDefmem(command);
79 } catch(std::string str) {
80 std::cout << str << std::endl;
81 } catch(char *str) {
82 std::cout << str << std::endl;
83 }
84 } else if(command.find(resetString) == 0) {
85 try {
86 doReset();
87 } catch(std::string str) {
88 std::cout << str << std::endl;
89 }
90 } else {
91 std::cout << "Comando inválido." << std::endl;
92 }
93 }
但有时它根本无法正确切换。有什么线索吗?
提前致谢,
编辑:
我做了一些测试,发现它落在最后一个 else-if 语句上,而不是落在最后一个 else 上。
然后我又检查了我的代码,发现根本原因是我忘记初始化resetString。
问题解决了!
谢谢大家。
你可能会期待find
当找到字符串时返回零,有点像这样strcmp
works.
但事实并非如此find
作品。find
返回找到的字符串的第一个索引,该索引可能为零,或者如果您要查找的字符串前面带有空格、其他字符串等,则该索引可能是其他索引。
If find
doesn't找到你要找的东西,它就会返回string::npos
。因此,您的 if...else 块应该检查是否找到字符串,而不是检查它们是否位于索引零。像这样:
if(command.find(helpString) != string::npos ) {
help();
} else if /// ... etc...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)